package com.infore.siteManagement.service.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.infore.siteManagement.PlatformInvocationServices.remoteService.IDataReceivingService;
import com.infore.siteManagement.constant.Constants;
import com.infore.siteManagement.constant.ResultConstants;
import com.infore.siteManagement.constant.StationConstant;
import com.infore.siteManagement.dao.IEntityManagerDao;
import com.infore.siteManagement.dto.AirInstructionsDataDto;
import com.infore.siteManagement.dto.StationDto;
import com.infore.siteManagement.dto.StationInfoDto;
import com.infore.siteManagement.dto.StationYunlInfoDto;
import com.infore.siteManagement.dto.StatisDataQueryVO;
import com.infore.siteManagement.dto.WaterInstructionsDataDto;
import com.infore.siteManagement.dto.YunlAppInfoParam;
import com.infore.siteManagement.entity.Area;
import com.infore.siteManagement.entity.Basinn;
import com.infore.siteManagement.entity.Item;
import com.infore.siteManagement.entity.ItemAndStation;
import com.infore.siteManagement.entity.ProjectAndStation;
import com.infore.siteManagement.entity.Station;
import com.infore.siteManagement.entity.StationAndApp;
import com.infore.siteManagement.entity.StationClassify;
import com.infore.siteManagement.entity.StationType;
import com.infore.siteManagement.entity.otherEntity.Customtree;
import com.infore.siteManagement.entity.otherEntity.TBranchOfc;
import com.infore.siteManagement.entity.otherEntity.TOpCen;
import com.infore.siteManagement.enums.AreaEnum;
import com.infore.siteManagement.enums.ResultStatus;
import com.infore.siteManagement.enums.StationFunctionEnum;
import com.infore.siteManagement.enums.SurfaceWaterTypes;
import com.infore.siteManagement.enums.WaterQualityTargetLevel;
import com.infore.siteManagement.externalInterface.IStatisticsAndAlarm;
import com.infore.siteManagement.externalInterface.IdentityManagement;
import com.infore.siteManagement.outEntity.SysUserStation;
import com.infore.siteManagement.repository.IAreaRespository;
import com.infore.siteManagement.repository.IBasinnRespository;
import com.infore.siteManagement.repository.ICustomRespository;
import com.infore.siteManagement.repository.IProjectAndStationRepository;
import com.infore.siteManagement.repository.IStationAndAppRepository;
import com.infore.siteManagement.repository.IStationRepository;
import com.infore.siteManagement.repository.IStationTypeRespository;
import com.infore.siteManagement.repository.IStationVievRepository;
import com.infore.siteManagement.repository.ISysUserStationRepository;
import com.infore.siteManagement.repository.ITPlatformCustomerStationRepository;
import com.infore.siteManagement.repository.IitemAndStationRepository;
import com.infore.siteManagement.repository.IitemRepository;
import com.infore.siteManagement.select.QueryDispatcher;
import com.infore.siteManagement.select.dto.QueryParamDto;
import com.infore.siteManagement.select.util.QueryUtil;
import com.infore.siteManagement.service.EntityObjectMapper;
import com.infore.siteManagement.service.IAreaService;
import com.infore.siteManagement.service.IFilterService;
import com.infore.siteManagement.service.StationService;
import com.infore.siteManagement.util.ArrayUtils;
import com.infore.siteManagement.util.DateUtil;
import com.infore.siteManagement.util.MyBeanUtils;
import com.infore.siteManagement.util.ObjectMapperUtil;
import com.infore.siteManagement.util.Page;
import com.infore.siteManagement.util.PageObject;
import com.infore.siteManagement.util.PageUtil;
import com.infore.siteManagement.util.ResultEntity;
import com.infore.siteManagement.util.StationRateUtil;
import com.infore.siteManagement.util.TreeToolUtils;
import com.infore.siteManagement.util.UUIDGenerator;
import com.infore.siteManagement.vo.ItemNameStationIdVo;
import com.infore.siteManagement.vo.MainStatisVO;
import com.infore.siteManagement.vo.MultiStatisVO;
import com.infore.siteManagement.vo.StationGisVo;
import com.infore.siteManagement.vo.StationTreeVO;
import com.infore.siteManagement.vo.StationTypeListVO;

/**
 * 
 * Copyright: Copyright (c) 2019
 * 
 * @ClassName: StationServiceImpl.java
 * @Description: 站点管理服务实现类
 *
 * @version: v1.0.0
 * @author: llf
 * @date: 2019
 */
@Service
public class StationServiceImpl implements StationService {

	@Autowired
	private IStationRepository iStationRepository;
	@Autowired
	private IAreaRespository iAreaRespository;
	@Autowired
	private QueryDispatcher queryDispatcher;
	@Autowired
	private IBasinnRespository iBasinnRespository;
	@Autowired
	private ICustomRespository iCustomRespository;
	@Autowired
	private IDataReceivingService iDataReceivingService;
	@Autowired
	private ObjectMapperUtil objectMapperUtil;
	@Autowired
	private IProjectAndStationRepository iProjectAndStationRepository;
	@Autowired
	private IEntityManagerDao iEntityManagerDao;
	@Autowired
	private IStationVievRepository iStationVievRepository;
	@Value("${fileRoot}")
	private String fileRoot;
	@Autowired
	private IFilterService iFilterService;
	@Autowired
	private IStationAndAppRepository iStationAndAppRepository;
	@Autowired
	private ISysUserStationRepository iSysUserStationRepository;
	@Autowired
	private IdentityManagement identityManagement;
	@Autowired
	private ITPlatformCustomerStationRepository platformCustomerStationRepository;
	@Autowired
	IStatisticsAndAlarm statisticsAndAlarm;
	@Autowired
	private StationRateUtil stationRateUtil;
	@Autowired
	EntityObjectMapper entityObjectMapper;
	@Autowired
	private IAreaService iAreaService;
	@Autowired
	private IStationTypeRespository stationTypeRespository;
	@Autowired
	private IitemRepository itemRepository;
	@Autowired
	private IitemAndStationRepository itemAndStationRepository;

	public ResultEntity editOrAddStation(StationDto stationDto) {
		String stationId = stationDto.getStationId();
		String stationCode = stationDto.getStationCode();
		String stationName = stationDto.getStationName();
//		String areaId = "ffbb7faf62044604bufae55675303cer";
		String basinId = "8ab380116a856f80016a85871add0000";
		String areaId = stationDto.getAreaId();
		String areaName = stationDto.getAreaName();
		String city = stationDto.getCity();
		String cityName = stationDto.getCityName();
		Integer controlorLevel = Integer.valueOf(stationDto.getControlorLevel());
		Double longitude = Double.valueOf(stationDto.getLongitude());
		Double latitude = Double.valueOf(stationDto.getLatitude());
		String stationAddress = stationDto.getStationAddress();
		String stationType = stationDto.getStationType();
		String targetLevel = stationDto.getTargetLevel();
		String monitorStatus = "1"; // 是否监控
		String enabled = "1"; // 是否验收
		String networking = "1"; // 是否联网
		if (StringUtils.isNotBlank(stationId)) { // id存在,则编辑
			iStationRepository.updateStationInfo(stationCode, stationName, areaId, basinId, controlorLevel, longitude,
					latitude, stationAddress, stationType, targetLevel, city, cityName, areaName, stationId);
		} else { // 新增
			stationId = UUIDGenerator.getUUID();
			iStationRepository.insertStationInfo(stationId, stationCode, stationName, areaId, basinId, controlorLevel,
					longitude, latitude, stationAddress, stationType, targetLevel, monitorStatus, enabled, networking,
					city, cityName, areaName);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS);
	}

	public ResultEntity queryStation(String stationCode) {
		List<Map<String, Object>> list = iStationRepository.selectStationInfo(stationCode);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity editStation(Station station) {
		// 如果id存在，进行编辑
		if (StringUtils.isNotBlank(station.getStationId())) {
			Station oldStation = iStationRepository.findById(station.getStationId()).orElse(null);
			if (oldStation != null) {// 如果存在则进行编辑，防止空值覆盖原有的值
				StationType oldStationtype = oldStation.getStationType();// type
				MyBeanUtils.copyNonNullProperties(station.getStationType(), oldStationtype);
				station.setStationType(oldStationtype);
				MyBeanUtils.copyNonNullProperties(station, oldStation);
				station = oldStation;
			} else {
				return new ResultEntity(ResultStatus.ERROR, ResultConstants.NO_SUCH_OBJECT);
			}
		} else {
		}
		try {
			iStationRepository.saveAndFlush(station);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.UPDATE_SUCCESS);
	}

	public ResultEntity queryStation(QueryParamDto queryParamDto) {
		// 站点无排序字段默认不排序
		if (org.springframework.util.StringUtils.isEmpty(queryParamDto)) {// 无任何条件查询
			List<Station> list = iStationRepository.findAll();
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.STATION_QUERY_SUCCESS).setDataList(list);
			// 仅分页查询
		} else if (!org.springframework.util.StringUtils.isEmpty(queryParamDto.getPageObject())
				&& org.springframework.util.StringUtils.isEmpty(queryParamDto.getQueryCondition())
				&& org.springframework.util.StringUtils.isEmpty(queryParamDto.getAssembleCondition())
				&& org.springframework.util.StringUtils.isEmpty(queryParamDto.getAssembleSql())) {
			org.springframework.data.domain.Page<Station> pageable = iStationRepository
					.findAll(queryParamDto.getPageObject().getPageRequest());
			Page<Station> page = PageUtil.pageConvert(pageable);
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.STATION_QUERY_SUCCESS).setPage(page);
			// 只传属性不传字段的查询
		} else if (StringUtils.isBlank(queryParamDto.getAssembleSql().getSelect())) {
			return this.queryAll(queryParamDto);
		}
		// 指定字段查询
		return queryDispatcher.dispatcher(queryParamDto, Station.class);
	}

	@SuppressWarnings("serial")
	public ResultEntity queryAll(QueryParamDto queryParamDto) {
		// 判断是否需要分页,不分页必须传null
		if (!org.springframework.util.StringUtils.isEmpty(queryParamDto.getPageObject())) {
			// 需要分页
			org.springframework.data.domain.Page<Station> pageAble = iStationRepository
					.findAll(new Specification<Station>() {

						public Predicate toPredicate(Root<Station> root, CriteriaQuery<?> query,
								CriteriaBuilder criteriaBuilder) {
							// 构建条件
							List<Predicate> predicates = com.infore.siteManagement.select.util.QueryUtil
									.createQueryCondition(queryParamDto, criteriaBuilder, root);
							// 组装条件
							Predicate predicate = com.infore.siteManagement.select.util.QueryUtil
									.assembleCondition(queryParamDto, criteriaBuilder, predicates);
							QueryUtil.assembleSql(queryParamDto, criteriaBuilder, query, root, predicate);
							return query.getRestriction();
						}
					}, queryParamDto.getPageObject().getPageRequest());
			Page<Station> page = PageUtil.pageConvert(pageAble);
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.STATION_QUERY_SUCCESS).setPage(page);
		} else {
			List<Station> list = iStationRepository.findAll(new Specification<Station>() {
				public Predicate toPredicate(Root<Station> root, CriteriaQuery<?> query,
						CriteriaBuilder criteriaBuilder) {
					// 构建条件
					List<Predicate> predicates = com.infore.siteManagement.select.util.QueryUtil
							.createQueryCondition(queryParamDto, criteriaBuilder, root);
					// 组装条件
					Predicate predicate = com.infore.siteManagement.select.util.QueryUtil
							.assembleCondition(queryParamDto, criteriaBuilder, predicates);
					QueryUtil.assembleSql(queryParamDto, criteriaBuilder, query, root, predicate);
					return query.getRestriction();
				}
			});
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.STATION_QUERY_SUCCESS).setDataList(list);
		}
	}

	public ResultEntity deleteStation(String ids) {
		try {
			List<String> idList = new ArrayList<String>();
			idList = ArrayUtils.stringToList(ids);
			// 删除jpa没有管理的中间表
			platformCustomerStationRepository.delByStationId(idList);
			iStationAndAppRepository.delByStationIdIn(idList);
			iSysUserStationRepository.delByStationId(idList);
			// 处理站点下站点照片
			try {
				List<Map<String, Object>> imageList = iStationRepository.selectAllImageByStationId(idList);
				List<String> imagesIds = new ArrayList<String>();
				for (Map<String, Object> map : imageList) {
					String outImages = map.get("OUT_IMAGE").toString();
					List<String> outImage = ArrayUtils.stringToList(outImages);
					String insideImages = map.get("INSIDE_IMAGE").toString();
					List<String> insideImage = ArrayUtils.stringToList(insideImages);
					String buildImages = map.get("BUILD_IMAGE").toString();
					List<String> buildImage = ArrayUtils.stringToList(buildImages);
					imagesIds.addAll(outImage);
					imagesIds.addAll(insideImage);
					imagesIds.addAll(buildImage);
					imagesIds.remove(null);
				}
				if (imagesIds.size() > 0) {
					for (String imagesId : imagesIds) {
						String path = fileRoot + imagesId;
						File file = new File(path);
						file.delete();
					}
				}
			} catch (Exception e) {
				// e.printStackTrace();
			}
			// 删除站点及关联表信息
			iStationRepository.deleteByStationIdIn(idList);
		} catch (Exception e) {
			return new ResultEntity(ResultStatus.ERROR, ResultConstants.STATION_DELETE_ERROR);
		}
		return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.STATION_DELETE_SUCCESS);
	}

	public ResultEntity validateStation(Station station) {
		// 验证站点和站点类型
		String message = StationConstant.STATION_SUCCESS;
		StationType stationtype = station.getStationType();
		if (("").equals(station.getStationName()) || station.getStationName() == null) {
			message = StationConstant.STATION_NAME_NULL;
		} else if (station.getStationName().length() > 200) {
			message = StationConstant.STATION_NAME_LENGTH;
		} else if (station.getStationAddress().length() > 200) {
			message = StationConstant.STATION_ADDRESS_LENGTH;
		} else if (station.getStationLeader().length() > 20) {
			message = StationConstant.STATION_LEADER_LENGTH;
		} else if (station.getLeaderTel().length() > 11) {
			message = StationConstant.STATION_LEADER_TEL_LENGTH;
		} else if (station.getOperCompanyName().length() > 100) {
			message = StationConstant.STATION_OPER_COMPANY_NAME_LENGTH;
		} else if (station.getOperCompanyLeader().length() > 50) {
			message = StationConstant.STATION_OPER_COMPANY_LEADER;
		} else if (station.getOperCompanyLeaderTel().length() > 50) {
			message = StationConstant.STATION_OPER_COMPANY_LEADER_TEL;
		} else if (stationtype.getStationTypeName().length() > 50) {
			message = StationConstant.STATION_TYPE_NAME_LENGTH;
		} else if (stationtype.getStationTypeCode().length() > 20) {
			message = StationConstant.STATION_TYPE_CODE_LENGTH;
		} else if (stationtype.getRemark().length() > 50) {
			message = StationConstant.STATION_TYPE_REMARK_LENGTH;
		}
		if (!message.equals(StationConstant.STATION_SUCCESS)) {
			return new ResultEntity(ResultStatus.ERROR, message);
		} else {
			return new ResultEntity(ResultStatus.SUCCESS, message);
		}

	}

	// 站点树中按条件筛选站点方法
	@SuppressWarnings(value = { "serial", "unchecked" })
	public List<Station> queryStationTreeUtil(String keyName, String typeCode, String isUsedString, String isMonitoring,
			String roleId) {
		List<Station> stations =
				// iStationRepository.findAll();
				iStationRepository.findAll(new Specification<Station>() {
					public Predicate toPredicate(Root<Station> root, CriteriaQuery<?> query,
							CriteriaBuilder criteriaBuilder) {
						List<Predicate> predicates = new ArrayList<Predicate>();
						// 根据站点类行code判断站点类型
						if (StringUtils.isNotBlank(typeCode)) {
							@SuppressWarnings("rawtypes")
							Join join = root.join("stationType");
							predicates
									.add(criteriaBuilder.equal(join.get("stationTypeCode").as(String.class), typeCode));
						}
						String userId = "";
						// 根据用户查询相关站点
						if (StringUtils.isNotBlank(userId)) {
							predicates.add(criteriaBuilder.equal(root.get("userId"), userId));
						}
						// 模糊查询站点名
						if (StringUtils.isNotBlank(keyName)) {
							predicates.add(criteriaBuilder.like(root.get("stationName"), "%" + keyName + "%"));
						}
						// 已建/验收使用
						if (StringUtils.isNotBlank(isUsedString)) {
							predicates.add(criteriaBuilder.equal(root.get("enabled"), Integer.valueOf(isUsedString)));
						}
						// 是否视频监控
						if (StringUtils.isNotBlank(isMonitoring)) {
							predicates.add(
									criteriaBuilder.equal(root.get("monitorStatus"), Integer.valueOf(isMonitoring)));
						}
						return query.where(predicates.toArray(new Predicate[predicates.size()]))
								.orderBy(criteriaBuilder.asc(root.get("stationMn"))).getRestriction();
					}
				});
		return stations;
	}

	/****/
	// 站点树中按条件筛选站点方法-----站点树专用
	@SuppressWarnings(value = { "serial", "unchecked" })
	public List<Station> treeUtil(String keyName, String typeCode, String isUsedString, String isMonitoring,
			HttpServletRequest request) {
		//
		List<Station> stations =
				// iStationRepository.findAll();
				iStationVievRepository.findAll(new Specification<Station>() {
					public Predicate toPredicate(Root<Station> root, CriteriaQuery<?> query,
							CriteriaBuilder criteriaBuilder) {
						List<Predicate> predicates = new ArrayList<Predicate>();
						// 根据站点类行code判断站点类型
						if (StringUtils.isNotBlank(typeCode)) {
							@SuppressWarnings("rawtypes")
							Join join = root.join("stationType");
							predicates
									.add(criteriaBuilder.equal(join.get("stationTypeCode").as(String.class), typeCode));
						}
						String userId = "";
						// 根据用户查询相关站点
						if (StringUtils.isNotBlank(userId)) {
							predicates.add(criteriaBuilder.equal(root.get("userId"), userId));
						}
						// 模糊查询站点名
						if (StringUtils.isNotBlank(keyName)) {
							predicates.add(criteriaBuilder.like(root.get("stationName"), "%" + keyName + "%"));
						}
						// 已建/验收使用
						if (StringUtils.isNotBlank(isUsedString)) {
							predicates.add(criteriaBuilder.equal(root.get("enabled"), Integer.valueOf(isUsedString)));
						}
						// 是否视频监控
						if (StringUtils.isNotBlank(isMonitoring)) {
							predicates.add(
									criteriaBuilder.equal(root.get("monitorStatus"), Integer.valueOf(isMonitoring)));
						}
						return query.where(predicates.toArray(new Predicate[predicates.size()]))
								.orderBy(criteriaBuilder.asc(root.get("stationMn"))).getRestriction();
					}
				});
		List<String> ids = iFilterService.getStationIdByCookie(request);
		stations = stations.stream().filter(f -> ids.contains(f.getStationId())).collect(Collectors.toList());
		return stations;
	}

	/** 查询站点树数据 **/
	List<Map<String, Object>> treeAreaUtilBySql(String keyName, String typeCode, String isUsedString,
			String isMonitoring, HttpServletRequest request) {
		List<Map<String, Object>> infos = new ArrayList<Map<String, Object>>();
		// 根据用户筛选站点
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
		// 模糊查询站点名
		if (StringUtils.isNotBlank(keyName)) {
			sBuilder.append(" and T.station_name like '%" + keyName + "%' ");
		}
		// 已建/验收使用
		if (StringUtils.isNotBlank(isUsedString)) {
			sBuilder.append(" and T.enabled = (" + isUsedString + ") ");
		}
		// 是否视频监控
		if (StringUtils.isNotBlank(isMonitoring)) {
			sBuilder.append(" and and T.monitor_status =(" + isMonitoring + ") ");
		}
		// 判断水质站与空气站 WQ\MM
		if (StringUtils.isNotBlank(typeCode)) {
			sBuilder.append(" and T.STATION_CLASSIFY_ID =\"" + typeCode + "\"");
		}
		// 过滤
		List<Object> sqls = iFilterService.getFilterSql(request, null);
		StringBuilder sBuilder2 = (StringBuilder) sqls.get(0);
		sBuilder2.append(sBuilder);
		leftJoin = (StringBuilder) sqls.get(1);
		String sql = "select T.station_name,T.station_mn,T.station_id,T.targer_water_quality,T.monitor_status,"
				+ "T.NETWORKING,T.enabled,T.station_type_id,a.area_id,a.area_code,a.parent_id,a.area_name,"
				+ "T.DEVICE_SERIAL from station T " + "left join area a on T.area_id = a.area_id " + leftJoin.toString()
				+ " where 1=1 " + " " + sBuilder2.toString() + " ";
		infos = iEntityManagerDao.getListMapBySQL(sql);
		return infos;
	}

	public ResultEntity queryStationTree(String keyName, String typeCode, String isUsedString, String isMonitoring,
			HttpServletRequest request) {
		List<Map<String, Object>> stations = treeAreaUtilBySql(keyName, typeCode, isUsedString, isMonitoring, request);// 通过条件的到站点
		if (stations == null || stations.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.NO_STATION_OBJECT).setDataList(null);
		}
		// 得到站点对应区域的code
		List<String> areaCodes = stations.stream().map(l -> l.get("AREA_CODE").toString()).distinct()
				.collect(Collectors.toList());
		// 拿到站点对应区域的所有区域和父区域

		List<Area> areas = iAreaRespository.queryAreaParent(areaCodes);
		// List<Area> areas = iAreaService.areaParents(String.join(",", areaCodes));
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		// 地区没有父节点的做根结点
		for (Area area : areas) {
			// 如果没有父节点getParentId做根结点
			if (StringUtils.isBlank(area.getParentId())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setNodeId(area.getAreaCode());
				stationTreeVO.setNodeName(area.getAreaName());
				stationTreeVO.setIsStation(false);
				stationTreeVO.setNodeType("area");
				stationTreeVO.setStructureType(area.getAreaLevel().getAreaLevelCode());
				stationTreeVO.setStationId(area.getAreaCode());
				rootList.add(stationTreeVO);
				// 如果有getParentId放到非根节点
			} else {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(area.getParentId());
				stationTreeVO.setNodeId(area.getAreaCode());
				stationTreeVO.setNodeName(area.getAreaName());
				stationTreeVO.setIsStation(false);
				stationTreeVO.setNodeType("area");
				stationTreeVO.setStationId(area.getAreaCode());
				stationTreeVO.setStructureType(area.getAreaLevel().getAreaLevelCode());
				bodyList.add(stationTreeVO);
			}
		}
		// 把站点放入集合
		for (Map<String, Object> station : stations) {
			// 确保站点有对应的流域
			if (StringUtils.isNotBlank(station.get("AREA_CODE").toString())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(station.get("AREA_CODE").toString());
				stationTreeVO.setNodeId(station.get("STATION_MN").toString());
				stationTreeVO.setNodeName(station.get("STATION_NAME").toString());
				stationTreeVO.setIsStation(true);
				stationTreeVO.setNodeType("station");
				stationTreeVO.setNetworking(Integer.parseInt(station.get("NETWORKING").toString()));
				stationTreeVO.setEnabled(Integer.parseInt(station.get("ENABLED").toString()));
				stationTreeVO.setStationId(station.get("STATION_ID").toString());
				// 默认无视频监控
				stationTreeVO.setMonitorStatus(Integer.parseInt(station.get("MONITOR_STATUS").toString()));
				stationTreeVO.setStructureType(AreaEnum.STATION.getResoString());
				stationTreeVO.setStationType1(
						station.get("STATION_TYPE_ID") == null ? "" : station.get("STATION_TYPE_ID").toString());
				stationTreeVO.setTargerWaterQuality(station.get("TARGER_WATER_QUALITY").toString());
				stationTreeVO.setAreaCode(station.get("AREA_CODE").toString());
				stationTreeVO.setAreaName(station.get("AREA_NAME").toString());
				stationTreeVO.setDeviceSerial(
						station.get("DEVICE_SERIAL") == null ? "" : station.get("DEVICE_SERIAL").toString());
//				stationTreeVO.setBasinCode(station.get("BASINN").toString());
//				stationTreeVO.setBasinName(station.get("AREA_CODE").toString());
				bodyList.add(stationTreeVO);
			}
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
//		
	}

	/** 查询站点流域树数据 **/
	List<Map<String, Object>> treeBasinnUtilBySql(String keyName, String typeCode, String isUsedString,
			String isMonitoring, HttpServletRequest request) {
		List<Map<String, Object>> infos = new ArrayList<Map<String, Object>>();
		// 根据用户筛选站点
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
		// 模糊查询站点名
		if (StringUtils.isNotBlank(keyName)) {
			sBuilder.append(" and s.station_name like '%" + keyName + "%' ");
		}
		// 已建/验收使用
		if (StringUtils.isNotBlank(isUsedString)) {
			sBuilder.append(" and s.enabled = to_number(" + isUsedString + ") ");
		}
		// 是否视频监控
		if (StringUtils.isNotBlank(isMonitoring)) {
			sBuilder.append(" and and s.monitor_status to_number(" + isMonitoring + ") ");
		}
		// 过滤
		List<Object> sqls = iFilterService.getFilterSql(request, null);
		sBuilder = (StringBuilder) sqls.get(0);
		leftJoin = (StringBuilder) sqls.get(1);
		String sql = "select t.station_name,t.station_mn,t.station_id,t.targer_water_quality,t.monitor_status,"
				+ "t.NETWORKING,t.enabled,t.station_type1,b.basinn_id,b.basinn_name,b.basinn_code,"
				+ "T.DEVICE_SERIAL from station t" + " left join basinn b on t.basinn_id = b.basinn_id " + leftJoin
				+ " where 1=1 " + sBuilder.toString() + "";
		infos = iEntityManagerDao.getListMapBySQL(sql);
		return infos;
	}

	public ResultEntity queryStationBasinnTree(String keyName, String typeCode, String isUsedString,
			String isMonitoring, HttpServletRequest request) {
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		// List<Basinn> basinns = iBasinnRespository.findAll();//所有流域集合
		List<String> basinnIds = new ArrayList<String>();// 存储筛选后站点对应流域
		List<Map<String, Object>> stations = treeBasinnUtilBySql(keyName, typeCode, isUsedString, isMonitoring,
				request);// 通过条件的到站点
		if (stations == null || stations.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, "数据为空站点不存在").setDataList(null);
		}
		basinnIds = stations.stream().map(l -> l.get("BASINN_ID").toString()).collect(Collectors.toList());
		List<Basinn> basinns = iBasinnRespository.findAllByBasinnIdIn(basinnIds);// 按条件筛选流域
		// 把流域集合放到rootList
		for (Basinn basinn : basinns) {
			StationTreeVO stationTreeVO = new StationTreeVO();
			stationTreeVO.setNodeId(basinn.getBasinnCode());
			stationTreeVO.setNodeName(basinn.getBasinnName());
			stationTreeVO.setIsStation(false);
			stationTreeVO.setNodeType("basinn");
			stationTreeVO.setStructureType(AreaEnum.BASINN.getResoString());
			stationTreeVO.setStationId(basinn.getBasinnCode());
			rootList.add(stationTreeVO);
		}
		// 把站点集合放到bodyList
		for (Map<String, Object> station : stations) {
			StationTreeVO stationTreeVO = new StationTreeVO();
			stationTreeVO.setPid(station.get("BASINN_CODE").toString());
			stationTreeVO.setNodeId(station.get("STATION_MN").toString());
			stationTreeVO.setNodeName(station.get("STATION_NAME").toString());
			stationTreeVO.setIsStation(true);
			stationTreeVO.setNodeType("station");
			stationTreeVO.setNetworking(Integer.parseInt(station.get("NETWORKING").toString()));
			stationTreeVO.setEnabled(Integer.parseInt(station.get("ENABLED").toString()));
			stationTreeVO.setStationId(station.get("STATION_ID").toString());
			// 默认无视频监控
			stationTreeVO.setMonitorStatus(Integer.parseInt(station.get("MONITOR_STATUS").toString()));
			stationTreeVO.setStructureType(AreaEnum.STATION.getResoString());
			stationTreeVO.setDeviceSerial(
					station.get("DEVICE_SERIAL") == null ? "" : station.get("DEVICE_SERIAL").toString());
			bodyList.add(stationTreeVO);
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	/**
	 * 通过session拿到用户/用户id 用户/用户id与分组名组成联合主键 -----Customtree
	 * 的uuid与Stationid组成联合主键------ 体现出多对多关系
	 * 
	 */
	public ResultEntity customStation(String userId, String groupName, String[] groupStations) {
		// 查询联合主键是否存在
		List<Customtree> listCustomtrees = iCustomRespository.findByCustomtreeUseridAndCustomtreeGroupname(userId,
				groupName);
		if (!org.springframework.util.StringUtils.isEmpty(listCustomtrees)) {
			return new ResultEntity(ResultStatus.ERROR, "组名已存在");
		}
		// 如果不存在 则创建一条与指定用户对应的组名包含站点
		Customtree customtree = new Customtree();
		customtree.setCustomtreeGroupname(groupName);// 设置组名
		customtree.setCustomtreeUserid(userId);// 用户名（唯一）
		List<String> idList = Arrays.asList(groupStations);
		List<Station> stations = iStationRepository.findAllByStationIdIn(idList);
		if (stations.size() > 0) {
			Set<Station> set = new HashSet<>(stations);
			customtree.setStations(set);// 设置组名下的站点
			try {
				iCustomRespository.saveAndFlush(customtree);
			} catch (Exception e) {
				e.printStackTrace();
				return new ResultEntity(ResultStatus.ERROR, Constants.SAVE_FAILUE);
			}
			return new ResultEntity(ResultStatus.SUCCESS, Constants.SAVE_SUCCESS);
		}
		return new ResultEntity(ResultStatus.ERROR, Constants.SAVE_FAILUE);
	}

	/**
	 * 返回自定义站点树
	 */
	public ResultEntity queryCustomStation(HttpServletRequest request, String keyName, String typeCode,
			String isUsedString, String isMonitoring) {
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		// List<Customtree> customtrees =
		// iCustomRespository.findByCustomtreeUserid(userId);//得到用户自定义站点树
		List<Station> stationsList = treeUtil(keyName, typeCode, isUsedString, isMonitoring, request);// 通过条件得到站点
		Set<Station> setModel = new HashSet<Station>(stationsList);// 把符合条件的站点集合放入到set中
		// 得到用户id下的所有站点
		List<Customtree> customtrees = iCustomRespository.findByCustomtreeUserid("");
		// 遍历放入集合中
		for (Customtree customtree : customtrees) {
			StationTreeVO stationTreeVO = new StationTreeVO();
			stationTreeVO.setNodeId(customtree.getCustomtreeId());
			stationTreeVO.setNodeName(customtree.getCustomtreeGroupname());
			stationTreeVO.setStructureType(AreaEnum.CUSTOM.getResoString());
			Set<Station> stations = customtree.getStations();
			// 取用户id下的站点和筛选后的站点的交集
			stations.retainAll(setModel);
			// 如果筛选后分组名下对应站点为空 则跳过本次组名循环 不添加到树中
			if ((stations.size() == 0) || (stations == null)) {
				continue;
			}
			rootList.add(stationTreeVO);// 把组名放入根结点集合
			for (Station station : stations) {
				StationTreeVO stationTreeVO1 = new StationTreeVO();
				stationTreeVO1.setPid(customtree.getCustomtreeId());
				stationTreeVO1.setNodeId(station.getStationMn());
				stationTreeVO1.setNodeName(station.getStationName());
				stationTreeVO1.setIsStation(true);
				stationTreeVO1.setStructureType(AreaEnum.STATION.getResoString());
				stationTreeVO1.setNetworking(station.getNetworking());
				stationTreeVO1.setEnabled(station.getEnabled().intValue());
				// 默认无视频监控
				int monitorStatus = station.getMonitorStatus() == null ? 0 : station.getMonitorStatus().intValue();
				stationTreeVO.setMonitorStatus(monitorStatus);
				bodyList.add(stationTreeVO1);// 把设备放入叶子节点集合
			}
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity updateCustom(String userId, String groupName, String newName, String[] newGroupStations) {
		Customtree customtree = iCustomRespository.findOneByCustomtreeUseridAndCustomtreeGroupname(userId, groupName);
		// 有新的分组名则设置新的分组名
		if (StringUtils.isNotBlank(newName)) {
			customtree.setCustomtreeGroupname(newName);
		}
		// 如果数组长度大于0（代表要更新自定义站点）则需要更新自定义组内的站点
		if (newGroupStations.length > 0 && !org.springframework.util.StringUtils.isEmpty(newGroupStations)) {
			List<String> idList = Arrays.asList(newGroupStations);
			List<Station> stations = iStationRepository.findAllByStationIdIn(idList);
			Set<Station> set = new HashSet<>(stations);
			customtree.setStations(set);
		}
		try {
			iCustomRespository.saveAndFlush(customtree);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultEntity(ResultStatus.ERROR, Constants.UPDATE_FAILUE);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.UPDATE_SUCCESS);
	}

	public ResultEntity deleteCustom(String userId, String groupName) {
		// 通过传入的用户名和组名（联合主键）找到唯一的一条记录 然后删除
		try {
			iCustomRespository.deleteByCustomtreeUseridAndCustomtreeGroupname(userId, groupName);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultEntity(ResultStatus.ERROR, Constants.DELETE_FAILUE);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.DELETE_SUCCESS);
	}

	@Override
	public List<StationTypeListVO> packStatonTypeListVP(HttpServletRequest request) {
		// List<Station> stations = queryStationTreeUtil("", "", "1", "",roleId);//
		// 通过条件的到站点
		String type = request.getParameter("type");
		// type = "WQ07,WQ08";
		if (StringUtils.isNotBlank(type)) {
			List<String> types = ArrayUtils.stringToList(type);
			type = ArrayUtils.convertListToString(types);
			if (StringUtils.isNotBlank(type)) {
				type = " and t.station_type_id in (" + type + ")";
			}
		} else {
			type = "";
		}
		List<Station> stations = getStationBasicByroleId(request, type, null);
		String mns = "";
		for (Station station : stations) {
			mns += station.getStationMn() + ",";
		}
		if (mns.length() > 1) {
			mns = mns.substring(0, mns.length() - 1);
		}
		if (mns.length() == 0) {
			return null;
		}
		ResultEntity res = iDataReceivingService.queryRowToColRealTimeData(mns, "1", "100000");
		Page<WaterInstructionsDataDto> page = objectMapperUtil.convertPage(res, WaterInstructionsDataDto.class);
		List<WaterInstructionsDataDto> dataList = page.getList();
		Map<String, WaterInstructionsDataDto> dataMap = new HashMap<>();
		for (WaterInstructionsDataDto dto : dataList) {
			dataMap.put(dto.getMn(), dto);
		}

		List<StationTypeListVO> list = new ArrayList<>();
		int all = 0;
		int normal = 0;
		int dataabnormal = 0;
		int linkabnormal = 0;
		WaterInstructionsDataDto dto = null;
		for (Station mv : stations) {
			String mn = mv.getStationMn();
			dto = dataMap.get(mn);
			if (dto == null) {
				linkabnormal++;
				continue;
			}
			boolean zc = true;
			String state = dto.getStationState();
			if ("0".equals(state)) {
				linkabnormal++;
				continue;
			}
			if ("2".equals(state)) {
				dataabnormal++;
				zc = false;
			}
			if (zc) {
				normal++;
			}
		}
		if (stations != null) {
			all = stations.size();
			StationTypeListVO rall = new StationTypeListVO();
			rall.setName("全部");
			rall.setNumber(all);
			rall.setType("all");

			StationTypeListVO rnormal = new StationTypeListVO();
			rnormal.setName("达标");
			rnormal.setNumber(normal);
			rnormal.setType("normal");

			StationTypeListVO rdataabnormal = new StationTypeListVO();
			rdataabnormal.setName("未达标");
			rdataabnormal.setNumber(dataabnormal);
			rdataabnormal.setType("dataAnomaly");

			StationTypeListVO rlinkabnormal = new StationTypeListVO();
			rlinkabnormal.setName("联网异常");
			rlinkabnormal.setNumber(linkabnormal);
			rlinkabnormal.setType("networkAnomaly");
			list.add(rall);
			list.add(rnormal);
			list.add(rdataabnormal);
			list.add(rlinkabnormal);

		}
		return list;
	}

	public List<MainStatisVO> allCateStatis(StatisDataQueryVO statisData, String statusType,
			HttpServletRequest request) {
		List<MainStatisVO> mainList = null;
		Map<String, MainStatisVO> mainMap = new HashMap<>();
		// 得到站点信息
		// List<Station> stations = queryStationTreeUtil("", "", "1", "",roleId);//
		// 权限筛选站点
		String type = request.getParameter("type");
		// type = "WQ07,WQ08";
		if (StringUtils.isNotBlank(type)) {
			List<String> types = ArrayUtils.stringToList(type);
			type = ArrayUtils.convertListToString(types);
			if (StringUtils.isNotBlank(type)) {
				type = " and t.station_type_id in (" + type + ")";
			}
		} else {
			type = "";
		}
		List<Station> stations = getStationBasicByroleId(request, type, null);
		String mns = "";
		List<String> ids = new ArrayList<String>(stations.size());
		for (Station station : stations) {
			mns += station.getStationMn() + ",";
			ids.add(station.getStationId());
		}
		if (mns.length() > 1) {
			mns = mns.substring(0, mns.length() - 1);
		}
		if (mns.length() == 0) {
			return mainList;
		}
		// 得到所有站点上传率有效率
		Date noeTime = new Date();
		String startTime = DateUtil.dateToString(noeTime, DateUtil.DATE_SMALL_STR) + " 00:00:00";
		String endTime = DateUtil.dateToString(noeTime, DateUtil.DATE_FULL_STR);
		Map<String, Object> rates = stationRateUtil.uploadRateReports(mns, startTime, endTime);
		//
		ResultEntity res = iDataReceivingService.queryRowToColRealTimeData(mns, "1", "100000");
		Page<WaterInstructionsDataDto> page = objectMapperUtil.convertPage(res, WaterInstructionsDataDto.class);
		List<WaterInstructionsDataDto> list = page.getList();
		Map<String, WaterInstructionsDataDto> dataMap = new HashMap<>();
		for (WaterInstructionsDataDto dto : list) {
			dataMap.put(dto.getMn(), dto);
		}
		Basinn basinn = null;
		WaterInstructionsDataDto data = null;
		Area area = null;
		String areaId = null;
		MainStatisVO main = null;
		String basinnId = null;
		List<MultiStatisVO> multiStatisVOs = null;
		MultiStatisVO stationVO = null;
		String queryType = statisData.getQueryType();
		String id = null, name = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 查询项目
		List<ItemNameStationIdVo> items = null;
		Map<String, ItemNameStationIdVo> itemNameStationMap = new HashMap<String, ItemNameStationIdVo>();
		if ("item".equals(queryType)) {
			items = itemRepository.queryItemNameStationId(ids);
			for (ItemNameStationIdVo itemNameStationIdVo : items) {
				itemNameStationMap.put(itemNameStationIdVo.getStationId(), itemNameStationIdVo);
			}
		}
		for (Station station : stations) {
			basinn = station.getBasinn();
			area = station.getArea();
			areaId = area.getAreaId();
			basinnId = basinn.getBasinnId();
			String mn = station.getStationMn();
			if ("area".equals(queryType)) {
				id = areaId;
				name = area.getAreaName();
			} else if ("river".equals(queryType)) {
				id = basinnId;
				name = basinn.getBasinnName();
			} else if ("item".equals(queryType)) {
				ItemNameStationIdVo itemNameStationIdVo = itemNameStationMap.get(station.getStationId());
				if (itemNameStationIdVo == null) {
					continue;
				}
				id = itemNameStationIdVo.getItemId();
				name = itemNameStationIdVo.getName();
			} else {
				continue;
			}
			// 联网计算
			String networkingRate = "0.0%"; // 联网率
			String effectiveRate = "0.0%"; // 有效率
			@SuppressWarnings("unchecked")
			Map<String, Object> rate = (Map<String, Object>) rates.get(mn);
			if (rate != null) {
				networkingRate = rate.get("up_rate").toString();
				effectiveRate = rate.get("enable_rate").toString();
			}
			//
			data = dataMap.get(station.getStationMn());
			stationVO = new MultiStatisVO();
			stationVO.setNetworkingRate(networkingRate);
			stationVO.setEffectiveRate(effectiveRate);
			stationVO.setName(station.getStationName());
			stationVO.setStationType(station.getStationType1());
			stationVO.setWaterQualityIndex(0.95);
			stationVO.setArea(station.getArea().getAreaName());
			stationVO.setRiver(basinn.getBasinnName());
			stationVO.setStationMn(station.getStationMn());
			stationVO.setLat(station.getLatitude());
			stationVO.setLng(station.getLongitude());
			String stationtype = station.getStationType() == null ? "" : station.getStationType().getStationTypeId();
			stationVO.setStationType(stationtype);
			if (data != null) {
				stationVO.setTime(data.getDataTime());
				stationVO.setEvaluation(data.getEvaluation());
				stationVO.setWaterQualityLevel(data.getWaterQuality());
				stationVO.setPrimaryPollutant(data.getPrimaryPollutant());
				stationVO.setStationState(data.getStationState());
			}
			@SuppressWarnings("unused")
			Date cDate = null;
			boolean bool = false;
			if (data != null && data.getDataTime() != null) {
				try {
					cDate = sdf.parse(data.getDataTime());
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if (statusType.equals("all")) {
				bool = true;
			} else if (statusType.equals("normal")) {
				if (data != null && data.getStationState().equals("1")) {
					bool = true;
				}
			} else if (statusType.equals("dataAnomaly")) {
				if (data != null && data.getStationState().equals("2")) {
					bool = true;
				}
			} else if (statusType.equals("networkAnomaly")) {
				if (data == null || data.getStationState().equals("0")) {
					bool = true;
				}
			}
			if (!bool) {
				continue;
			}
			if (mainMap.get(id) == null && area.getParentId() != null) {
				main = new MainStatisVO();
				main.setCount(1);
				multiStatisVOs = new ArrayList<>();
				multiStatisVOs.add(stationVO);
				main.setMultiStatisVOs(multiStatisVOs);
				main.setName(name);
				if (data != null) {
					main.setEvaluation(data.getEvaluation());
				}
				mainMap.put(id, main);
			} else if (mainMap.get(id) != null && area.getParentId() != null) {
				mainMap.get(id).setCount(mainMap.get(id).getCount() + 1);
				mainMap.get(id).getMultiStatisVOs().add(stationVO);
			}

		}
		mainList = new ArrayList<>(mainMap.values());
		return mainList;
	}

	public ResultEntity queryStationInfoByMn(String mn) {
		Station station = iStationRepository.findOneByStationMn(mn);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(station);
	}

	public ResultEntity queryAllStationInfo(HttpServletRequest request) {
		// List<Station> stations = queryStationTreeUtil("", "", "1", "",roleId);//
		// 通过条件的到站点
		String type = request.getParameter("type");
		// type = "WQ07,WQ08";
		if (StringUtils.isNotBlank(type)) {
			List<String> types = ArrayUtils.stringToList(type);
			type = ArrayUtils.convertListToString(types);
			if (StringUtils.isNotBlank(type)) {
				type = " and t.station_type_id in (" + type + ")";
			}
		} else {
			type = "";
		}
		List<Station> stations = getStationBasicByroleId(request, type, null);
		String mns = "";
		List<MultiStatisVO> result = new ArrayList<>();
		MultiStatisVO vo = null;
		for (Station station : stations) {
			vo = new MultiStatisVO();
			mns += station.getStationMn() + ",";
			vo.setName(station.getStationName());
			vo.setLat(station.getLatitude());
			vo.setLng(station.getLongitude());
			vo.setStationMn(station.getStationMn());
			String stationtype = station.getStationType() == null ? "" : station.getStationType().getStationTypeId();
			vo.setStationType(stationtype);
			vo.setTargetQualityLevel(station.getTargerWaterQuality());
			result.add(vo);
		}
		if (mns.length() > 1) {
			mns = mns.substring(0, mns.length() - 1);
		}
		ResultEntity res = iDataReceivingService.queryRealTimeWaterQualitySort(mns);
		List<WaterInstructionsDataDto> waterList = objectMapperUtil.convertList(res, WaterInstructionsDataDto.class);
		Map<String, WaterInstructionsDataDto> waterMap = new HashMap<>();
		for (WaterInstructionsDataDto data : waterList) {
			waterMap.put(data.getMn(), data);
		}
		WaterInstructionsDataDto data = null;
		for (MultiStatisVO multiStatisVO : result) {
			data = waterMap.get(multiStatisVO.getStationMn());
			if (data == null)
				continue;
			multiStatisVO.setEvaluation(data.getEvaluation());
			multiStatisVO.setPrimaryPollutant(data.getPrimaryPollutant());
			multiStatisVO.setTime(data.getDataTime());
			multiStatisVO.setWaterQualityLevel(data.getWaterQuality());
			multiStatisVO.setStationState(data.getStationState());
		}

		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(result);
	}

	@Override
	public ResultEntity queryControlTree(String keyName, String typeCode, String string, String isMonitoring) {
		List<Station> stations = queryStationTreeUtil(keyName, typeCode, string, isMonitoring, "");// 通过条件的到站点
		if (stations == null || stations.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.NO_STATION_OBJECT).setDataList(null);
		}
		// 得到站点对应区域的code
		Set<String> areaCodes = new HashSet<String>();
		for (Station station : stations) {
			areaCodes.add(station.getArea().getAreaCode());
		}
		// 拿到站点对应区域的所有区域和父区域
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		// 地区没有父节点的做根结点
//		for (Area area : areas) {
//			//如果没有父节点getParentId做根结点
//			if (org.springframework.util.StringUtils.isEmpty(area.getParentId())) {
//				StationTreeVO stationTreeVO = new StationTreeVO();
//				stationTreeVO.setNodeId(area.getAreaCode());
//				stationTreeVO.setNodeName(area.getAreaName());
//				stationTreeVO.setIsStation(false);
//				stationTreeVO.setStructureType(area.getAreaLevel().getAreaLevelCode());
//				rootList.add(stationTreeVO);
//				//如果有getParentId放到非根节点
//			}else {
//				if (!(area.getAreaName().equals("水站") || area.getAreaName().equals("污染源"))) {
//					StationTreeVO stationTreeVO = new StationTreeVO();
//					stationTreeVO.setPid(area.getParentId());
//					stationTreeVO.setNodeId(area.getAreaCode());
//					stationTreeVO.setNodeName(area.getAreaName());
//					stationTreeVO.setIsStation(false);
//					stationTreeVO.setStructureType(area.getAreaLevel().getAreaLevelCode());
//					bodyList.add(stationTreeVO);
//				}
//				
//			}
//		}

		//
		for (int i = 0; i < 4; i++) {
			StationTreeVO VO = new StationTreeVO();
			VO.setIsStation(false);
			if (i == 0) {
				VO.setNodeId(0 + "conrtol");
				VO.setNodeName("国控");
			} else if (i == 1) {
				VO.setNodeId(1 + "conrtol");
				VO.setNodeName("省控");
			} else if (i == 2) {
				VO.setNodeId(2 + "conrtol");
				VO.setNodeName("市控/州控");
			} else if (i == 3) {
				VO.setNodeId(3 + "conrtol");
				VO.setNodeName("县控/区控");
			}
//			else if (i == 4) {
//				VO.setNodeId(4+"conrtol");
//				VO.setNodeName("非控");
//			}
			VO.setStructureType(AreaEnum.CITY.getResoString());
			rootList.add(VO);
		}
		// 把站点放入集合
		for (Station station : stations) {
			// 确保站点有对应的流域
			if (StringUtils.isNotBlank(station.getArea().getAreaCode())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				//
				if (station.getControlorLevel().equals(0)) {
					stationTreeVO.setPid(0 + "conrtol");
				} else if (station.getControlorLevel().equals(1)) {
					stationTreeVO.setPid(1 + "conrtol");
				} else if (station.getControlorLevel().equals(2)) {
					stationTreeVO.setPid(2 + "conrtol");
				} else if (station.getControlorLevel().equals(3)) {
					stationTreeVO.setPid(3 + "conrtol");
				}
//				else if (station.getControlorLevel().equals(4)) {
//					stationTreeVO.setPid(4+"conrtol");
//				}
				//
				stationTreeVO.setNodeId(station.getStationMn());
				stationTreeVO.setNodeName(station.getStationName());
				stationTreeVO.setIsStation(true);
				stationTreeVO.setNetworking(station.getNetworking());
				stationTreeVO.setEnabled(station.getEnabled().intValue());
				// 默认无视频监控
				int monitorStatus = station.getMonitorStatus() == null ? 0 : station.getMonitorStatus().intValue();
				stationTreeVO.setMonitorStatus(monitorStatus);
				stationTreeVO.setStructureType(AreaEnum.STATION.getResoString());
				stationTreeVO.setStationType1(station.getStationType1());
				stationTreeVO.setTargerWaterQuality(station.getTargerWaterQuality());
				stationTreeVO.setAreaCode(station.getArea().getAreaCode());
				stationTreeVO.setAreaName(station.getArea().getAreaName());
				stationTreeVO.setBasinCode(station.getBasinn().getBasinnCode());
				stationTreeVO.setBasinName(station.getBasinn().getBasinnName());
				bodyList.add(stationTreeVO);
			}
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
//		
	}

	public ResultEntity addImageOut(MultipartFile[] files, String mn, String type) {
		if (files.length == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_FAILUE);
		}
		try {
			String filePath = fileRoot;
			File fileMkdir = new File(filePath);// 判断文件目录是否存在
			if (!fileMkdir.exists()) {
				fileMkdir.mkdir();
			}
			String imageName = iStationRepository.selectOutImageInfo(mn);
//				if (StringUtils.isBlank(imageName)) {
//					return new ResultEntity(ResultStatus.SUCCESS,"站点信息错误");
//				}
			for (MultipartFile multipartFile : files) {
				if (multipartFile.isEmpty()) {
					return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_FAILUE);
				}
				// 取得当前上传文件的文件名称
				String originalFilename = multipartFile.getOriginalFilename();
				// 得到文件后缀
				String[] fileName = originalFilename.split("\\.");
				// 生成文件名
				String name = UUIDGenerator.getUUID() + "." + fileName[1];
				// FileUtils.uploadFile(fileBytes, filePath, name);
				File file = new File(filePath, name);
				multipartFile.transferTo(file);
				if (org.springframework.util.StringUtils.isEmpty(imageName)) {
					imageName = name;
				} else {
					imageName = imageName + "," + name;
				}
			}
			iStationRepository.updateImageInfo(mn, imageName);
		} catch (Exception e) {
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_SUCCESS);
	}

	public ResultEntity addImageInside(MultipartFile[] files, String mn, String type) {
		if (files.length == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_FAILUE);
		}
		try {
			String filePath = fileRoot;
			File fileMkdir = new File(filePath);// 判断文件目录是否存在
			if (!fileMkdir.exists()) {
				fileMkdir.mkdir();
			}
			String imageName = iStationRepository.selectInsideImageInfo(mn);
//				if (StringUtils.isBlank(imageName)) {
//					return new ResultEntity(ResultStatus.SUCCESS,"站点信息错误");
//				}
			for (MultipartFile multipartFile : files) {
				if (multipartFile.isEmpty()) {
					return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_FAILUE);
				}
				// 取得当前上传文件的文件名称
				String originalFilename = multipartFile.getOriginalFilename();
				// 得到文件后缀
				String[] fileName = originalFilename.split("\\.");
				// 生成文件名
				String name = UUIDGenerator.getUUID() + "." + fileName[1];
				// FileUtils.uploadFile(fileBytes, filePath, name);
				File file = new File(filePath, name);
				multipartFile.transferTo(file);
				if (org.springframework.util.StringUtils.isEmpty(imageName)) {
					imageName = name;
				} else {
					imageName = imageName + "," + name;
				}
			}
			iStationRepository.updateImageInside(mn, imageName);
		} catch (Exception e) {
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_SUCCESS);
	}

	public ResultEntity addImageBuild(MultipartFile[] files, String mn, String type) {
		if (files.length == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_FAILUE);
		}
		try {
			String filePath = fileRoot;
			File fileMkdir = new File(filePath);// 判断文件目录是否存在
			if (!fileMkdir.exists()) {
				fileMkdir.mkdir();
			}
			String imageName = iStationRepository.selectBuildImageInfo(mn);
//				if (StringUtils.isBlank(imageName)) {
//					return new ResultEntity(ResultStatus.SUCCESS,"站点信息错误");
//				}
			for (MultipartFile multipartFile : files) {
				if (multipartFile.isEmpty()) {
					return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_FAILUE);
				}
				// 取得当前上传文件的文件名称
				String originalFilename = multipartFile.getOriginalFilename();
				// 得到文件后缀
				String[] fileName = originalFilename.split("\\.");
				// 生成文件名
				String name = UUIDGenerator.getUUID() + "." + fileName[1];
				// FileUtils.uploadFile(fileBytes, filePath, name);
				File file = new File(filePath, name);
				multipartFile.transferTo(file);
				if (org.springframework.util.StringUtils.isEmpty(imageName)) {
					imageName = name;
				} else {
					imageName = imageName + "," + name;
				}
			}
			iStationRepository.updateImageBuild(mn, imageName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_SUCCESS);
	}

	public ResultEntity deleteImage(String path, String mn, String type) {
		int lastIndexOf = path.lastIndexOf("/");
		// 截取文件名
		String sbs = path.substring(lastIndexOf + 1, path.length());
		// 拼接文件地址
		String sb = fileRoot + sbs;
		File file = new File(sb);
		if (file.exists()) {
			// 删除文件并且更新数据库信息
			if (file.delete()) {
				String imageName = "";
				// 判断图片的类型
				if (type.equals("out")) {
					imageName = iStationRepository.selectOutImageInfo(mn);
				} else if (type.equals("inside")) {
					imageName = iStationRepository.selectInsideImageInfo(mn);
				} else if (type.equals("build")) {
					imageName = iStationRepository.selectBuildImageInfo(mn);
				}
				// 更新数据库的图片名称字符串 拼接上逗号 将要删除的文件名用空代替
				imageName = "," + imageName;
				if (imageName.contains("," + sbs)) {
					imageName = imageName.replace("," + sbs, "");
				}
				// 如果拼接在首位去掉第一个多余的字符串
				if (imageName.substring(0, 1).equals(",")) {
					imageName = imageName.substring(1);
				}
				if (type.equals("out")) {
					iStationRepository.updateImageInfo(mn, imageName);
				} else if (type.equals("inside")) {
					iStationRepository.updateImageInside(mn, imageName);
				} else if (type.equals("build")) {
					iStationRepository.updateImageBuild(mn, imageName);
				}
				return new ResultEntity(ResultStatus.SUCCESS, Constants.UPDATE_SUCCESS).setInfo("删除照片成功");
			} else {
				return new ResultEntity(ResultStatus.SUCCESS, Constants.UPDATE_FAILUE).setInfo("删除照片失败");
			}
		} else {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.UPDATE_FAILUE).setInfo("删除照片失败");
		}

	}

	public ResultEntity queryImage(String mn) {
		List<Map<String, Object>> image = iStationRepository.selectAllImage(mn);
		if (image.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, "当前站点无信息");
		}
		// 结果集
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		Map<String, Object> maps = image.get(0);
		for (String key : maps.keySet()) {
			// 照片地址
			List<String> urls = new ArrayList<String>();
			List<String> paths = new ArrayList<String>();
			String value = "";
			Map<String, Object> map = new HashMap<String, Object>();
			if (StringUtils.isNotBlank((String) maps.get(key))) {
				value = maps.get(key).toString();
				urls = Arrays.asList(value.split(","));
				for (String url : urls) {
					// String path = fileRoot + url;
					paths.add(url);
				}
			}
			map.put("type", key);
			map.put("path", paths);
			result.add(map);
		}

		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(result);
	}

	public ResultEntity querySurfaceWaterTypes() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (SurfaceWaterTypes e : SurfaceWaterTypes.values()) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", e.getStatusCode() + "");
			map.put("name", e.getReasonPhrase());
			list.add(map);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity queryTargetLevel() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (WaterQualityTargetLevel e : WaterQualityTargetLevel.values()) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", e.getStatusCode() + "");
			map.put("name", e.getReasonPhrase());
			list.add(map);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity queryFunction() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (StationFunctionEnum e : StationFunctionEnum.values()) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", e.getStatusCode() + "");
			map.put("name", e.getReasonPhrase());
			list.add(map);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity editOrAddStation(StationInfoDto stationInfoDto) {
		// 字段长度校验
//		try {
//			DataLenCheckHelper.checkAttributeValueLen(stationInfoDto);
//		} catch (Exception e3) {
//			// TODO Auto-generated catch block
//			// e3.printStackTrace();
//			return new ResultEntity(ResultStatus.ERROR, e3.getMessage());
//		}
		// 运营中心
		String opcenId = stationInfoDto.getOpcenId() == null ? "" : stationInfoDto.getOpcenId();
		String opcenName = "";
		if (StringUtils.isNotBlank(opcenId)) {
			ResultEntity opcEntity = identityManagement.getTOpCenById(opcenId);
			TOpCen opCen = objectMapperUtil.convertObject(opcEntity, TOpCen.class);
			opcenName = opCen.getOpName();
		}
		// 运营分公司及人员
		String operCompanyName = "";
		try {
			String filialeId = stationInfoDto.getOperCompanyId() == null ? "" : stationInfoDto.getOperCompanyId();
			ResultEntity filRes = identityManagement.getTBranchOfcById(filialeId);
			TBranchOfc tBranchOfc = objectMapperUtil.convertObject(filRes, TBranchOfc.class);
			if (tBranchOfc != null) {
				operCompanyName = tBranchOfc.getBranchName() == null ? "" : tBranchOfc.getBranchName();
			}
		} catch (Exception e2) {
			// e2.printStackTrace();
		}
		// 站点负责人
		String stationLeader = "";
		String stationLeaderId = stationInfoDto.getStationLeaderId() == null ? "" : stationInfoDto.getStationLeaderId();
		if (StringUtils.isNotBlank(stationLeaderId)) {
			ResultEntity userEntity = identityManagement.getUserByIds(stationLeaderId);
			List<Map<String, Object>> users = objectMapperUtil.convertListMap(userEntity);
			if (users != null && users.size() > 0) {
				stationLeader = users.get(0).get("userName").toString();
			}
		}
		//
		String areaid = stationInfoDto.getAreaId() == null ? "" : stationInfoDto.getAreaId();
		Area area = iAreaRespository.findById(areaid).orElse(null);
		String areaName = "";
		if (area != null) {
			areaName = area.getAreaName() == null ? "" : area.getAreaName();
		}
		String basinId = stationInfoDto.getBasinId() == null ? "" : stationInfoDto.getBasinId();
		Basinn basinn = iBasinnRespository.findById(basinId).orElse(null);
		String basinName = basinn.getBasinnName() == null ? "" : basinn.getBasinnName();
		String city = stationInfoDto.getCity() == null ? "" : stationInfoDto.getCity();
		Area cityA = iAreaRespository.findById(city).orElse(null);
		String cityName = "";
		if (cityA != null) {
			cityName = cityA.getAreaName() == null ? "" : cityA.getAreaName();
		}
		String controlorLevel = stationInfoDto.getControlorLevel() == null ? null : stationInfoDto.getControlorLevel();
		String enabled = stationInfoDto.getEnabled() == null ? "1" : stationInfoDto.getEnabled();
		String enabledTime = "";
		Date enabledTimeDate = new Date();// 如果时间参数为null,则获取系统时间
		if (StringUtils.isNotBlank(stationInfoDto.getEnabledTime())) {
			enabledTime = stationInfoDto.getEnabledTime();
			enabledTimeDate = DateUtil.stringToDate(enabledTime, DateUtil.DATE_FULL_STR);
		} else {
			enabledTimeDate = DateUtil.getSystemTime();
		}
		Float latitudeFloat = 0.0F;
		String latitude = stationInfoDto.getLatitude() == null ? "0.0" : stationInfoDto.getLatitude();
		latitudeFloat = Float.parseFloat(latitude);
		String localManagementUnits = stationInfoDto.getLocalManagementUnits() == null ? ""
				: stationInfoDto.getLocalManagementUnits();
		Float longitudeFloat = 0.0F;
		String longitude = stationInfoDto.getLongitude() == null ? "0.0" : stationInfoDto.getLongitude();
		longitudeFloat = Float.parseFloat(longitude);
		String provinceId = stationInfoDto.getProvinceId() == null ? "" : stationInfoDto.getProvinceId();
		Area province = iAreaRespository.findById(provinceId).orElse(null);
		String provinceName = "";
		if (province != null) {
			provinceName = province.getAreaName() == null ? null : province.getAreaName();
		}
		String sort = stationInfoDto.getSort() == null ? null : stationInfoDto.getSort();
		String stationAddress = stationInfoDto.getStationAddress() == null ? null : stationInfoDto.getStationAddress();
		String stationCode = stationInfoDto.getStationCode() == null ? null : stationInfoDto.getStationCode();
		String stationId = stationInfoDto.getStationId() == null ? null : stationInfoDto.getStationId();
		String stationName = stationInfoDto.getStationName() == null ? null : stationInfoDto.getStationName();
		String stationPassworld = stationInfoDto.getStationPassworld() == null ? ""
				: stationInfoDto.getStationPassworld();
		String stationProperty = stationInfoDto.getStationProperty() == null ? null
				: stationInfoDto.getStationProperty();
		String stationProvincesUpDown = stationInfoDto.getStationProvincesUpDown() == null ? ""
				: stationInfoDto.getStationProvincesUpDown();
		String stationType = stationInfoDto.getStationType() == null ? null : stationInfoDto.getStationType();
		String stationClassify = stationInfoDto.getStationClassify() == null ? null
				: stationInfoDto.getStationClassify();
		String targetLevel = stationInfoDto.getTargetLevel() == null ? null : stationInfoDto.getTargetLevel();
		String stationRiver = stationInfoDto.getStationRiver() == null ? null : stationInfoDto.getStationRiver();
		String stationFunction = stationInfoDto.getStationFunction() == null ? null
				: stationInfoDto.getStationFunction();
		String operCompanyId = stationInfoDto.getOperCompanyId() == null ? null : stationInfoDto.getOperCompanyId();
		String stationBriefInfo = stationInfoDto.getStationBriefInfo() == null ? null
				: stationInfoDto.getStationBriefInfo();
		String peripheralHistory = stationInfoDto.getPeripheralHistory() == null ? null
				: stationInfoDto.getPeripheralHistory();
		String surfaceWaterTypes = stationInfoDto.getSurfaceWaterTypes() == null ? null
				: stationInfoDto.getSurfaceWaterTypes();
		String dataFrequency = stationInfoDto.getDataFrequency() == null ? null : stationInfoDto.getDataFrequency();
		String stationType1 = stationInfoDto.getStationType1() == null ? "001" : stationInfoDto.getStationType1();
		String keyPerson = stationInfoDto.getKeyPerson() == null ? null : stationInfoDto.getKeyPerson();
		String isSpecialBusiness = stationInfoDto.getIsSpecialBusiness() == null ? ""
				: stationInfoDto.getIsSpecialBusiness();
		String kil = stationInfoDto.getKil() == null ? null : stationInfoDto.getKil();
		String stationLevel = stationInfoDto.getStationLevel() == null ? null : stationInfoDto.getStationLevel();
		// 用于返回mn号
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map = new HashMap<String, String>();
		map.put("stationMn", stationCode);
		map.put("stationId", stationId);
		list.add(map);
		// 维护因子
		// 关联站点和因子
		String projectCode = stationInfoDto.getProjectCodes();
		if (StringUtils.isNotBlank(projectCode)) {
			List<String> projectCodesList = ArrayUtils.stringToList(projectCode);
			List<String> projectCodes = projectCodesList.stream()
					.filter(f -> StringUtils.isNotBlank(f) && (!isContainChinese(f))).collect(Collectors.toList());
			List<ProjectAndStation> projectAndStations = new ArrayList<ProjectAndStation>();
			for (String string : projectCodes) {
				ProjectAndStation projectAndStation = new ProjectAndStation();
				projectAndStation.setStationCode(stationCode);
				projectAndStation.setProjectCode(string);
				projectAndStations.add(projectAndStation);
			}
			try {
				// 先删除站点下的因子
				if (StringUtils.isNotBlank(stationCode)) {
					List<String> stationCodes = new ArrayList<String>();
					stationCodes.add(stationCode);
					iProjectAndStationRepository.deleteByStationCodeIn(stationCodes);
					iProjectAndStationRepository.flush();
				}
				iProjectAndStationRepository.saveAll(projectAndStations);
				map.put("projectCode", projectCode);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

		// 如果站点id不为空则进行编辑，否则新增
		if (StringUtils.isEmpty(stationId)) {
			stationId = UUIDGenerator.getUUID();
			// 新增站点时判断mn是否存在
			List<String> mn = new ArrayList<String>();
			mn.add(stationCode);
			List<Station> station = iStationRepository.findAllByStationMnIn(mn);
			if (station.size() != 0) {
				return new ResultEntity(ResultStatus.SUCCESS, Constants.INSERT_FAILUE).setInfo("站点mn号已存在");
			}
			try {
				iStationRepository.insertStationAllInfo(areaid, areaName, basinId, basinName, city, cityName,
						controlorLevel, enabled, enabledTimeDate, latitudeFloat, localManagementUnits, longitudeFloat,
						provinceId, provinceName, sort, stationAddress, stationCode, stationId, stationName,
						stationPassworld, stationProperty, stationProvincesUpDown, stationType, stationClassify,
						targetLevel, stationRiver, stationFunction, operCompanyId, operCompanyName, stationBriefInfo,
						peripheralHistory, surfaceWaterTypes, dataFrequency, stationType1, keyPerson, isSpecialBusiness,
						kil, stationLevel, stationLeaderId, stationLeader, opcenId, opcenName);
				// 维护站点和系统中间表
				if (StringUtils.isNotBlank(stationId)) {
					String appCode = stationInfoDto.getAppCode() == null ? "" : stationInfoDto.getAppCode();
					iStationAndAppRepository.delByStationIdAndPlat(stationId, appCode);
					if (StringUtils.isNotBlank(appCode)) {
						StationAndApp stationAndApp = new StationAndApp();
						stationAndApp.setAppCode(appCode);
						stationAndApp.setStationMn(stationCode);
						stationAndApp.setStationId(stationId);
						iStationAndAppRepository.save(stationAndApp);
					}
				}
				// 维护用户id和站点中间表
				String userId = stationInfoDto.getUserId() == null ? "" : stationInfoDto.getUserId();
				if (StringUtils.isNotBlank(userId)) {
					// iSysUserStationRepository.delByUserId(userId);
					SysUserStation sysUserStation = new SysUserStation();
					sysUserStation.setStationId(stationId);
					sysUserStation.setUserId(userId);
					iSysUserStationRepository.save(sysUserStation);
					// 判断负责人
					if (StringUtils.isNotBlank(stationLeaderId) && !userId.equals(stationLeaderId)) {
						SysUserStation stationLeaderAnd = new SysUserStation();
						stationLeaderAnd.setStationId(stationId);
						stationLeaderAnd.setUserId(stationLeaderId);
						iSysUserStationRepository.save(stationLeaderAnd);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return new ResultEntity(ResultStatus.ERROR, Constants.INSERT_FAILUE);
			}
			return new ResultEntity(ResultStatus.SUCCESS, Constants.INSERT_SUCCESS).setInfo(list);
		} else {
			try {
				iStationRepository.updateStationAllInfo(areaid, areaName, basinId, basinName, city, cityName,
						controlorLevel, enabled, enabledTimeDate, latitudeFloat, localManagementUnits, longitudeFloat,
						provinceId, provinceName, sort, stationAddress, stationCode, stationId, stationName,
						stationPassworld, stationProperty, stationProvincesUpDown, stationType, stationClassify,
						targetLevel, stationRiver, stationFunction, operCompanyId, operCompanyName, stationBriefInfo,
						peripheralHistory, surfaceWaterTypes, dataFrequency, stationType1, keyPerson, isSpecialBusiness,
						kil, stationLevel, stationLeaderId, stationLeader, opcenId, opcenName);
				// 维护站点和系统中间表
				if (StringUtils.isNotBlank(stationId)) {
					String appCode = stationInfoDto.getAppCode() == null ? "" : stationInfoDto.getAppCode();
					iStationAndAppRepository.delByStationIdAndPlat(stationId, appCode);
					if (StringUtils.isNotBlank(appCode)) {
						StationAndApp stationAndApp = new StationAndApp();
						stationAndApp.setAppCode(appCode);
						stationAndApp.setStationMn(stationCode);
						stationAndApp.setStationId(stationId);
						iStationAndAppRepository.save(stationAndApp);
					}
				}
				// 维护用户id和站点中间表
				String userId = stationInfoDto.getUserId() == null ? "" : stationInfoDto.getUserId();
				if (StringUtils.isNotBlank(userId)) {
					iSysUserStationRepository.delByUserIdAndStation(userId, stationId);
					SysUserStation sysUserStation = new SysUserStation();
					sysUserStation.setStationId(stationId);
					sysUserStation.setUserId(userId);
					iSysUserStationRepository.save(sysUserStation);
				}
				// 判断负责人
				if (StringUtils.isNotBlank(stationLeaderId) && !userId.equals(stationLeaderId)) {
					iSysUserStationRepository.delByUserIdAndStation(stationLeaderId, stationId);
					SysUserStation stationLeaderAnd = new SysUserStation();
					stationLeaderAnd.setStationId(stationId);
					stationLeaderAnd.setUserId(stationLeaderId);
					iSysUserStationRepository.save(stationLeaderAnd);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return new ResultEntity(ResultStatus.ERROR, Constants.UPDATE_FAILUE);
			}
			return new ResultEntity(ResultStatus.SUCCESS, Constants.UPDATE_SUCCESS).setInfo(list);
		}
	}

	public boolean isContainChinese(String str) {
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	public ResultEntity singleStationInfo(String areaId, String stationName,
			com.infore.siteManagement.select.util.PageObject pageObject, HttpServletRequest request) {
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
		// 过滤
		List<Object> sqls = iFilterService.getFilterSql(request, null);
		sBuilder = (StringBuilder) sqls.get(0);
		leftJoin = (StringBuilder) sqls.get(1);
		if (StringUtils.isNotBlank(areaId)) {
			areaId = " and T.province_id = '" + areaId + "'";
			sBuilder.append(areaId);
		}
		if (StringUtils.isNotBlank(stationName)) {
			stationName = " and T.station_name like '%" + stationName + "%'";
			sBuilder.append(stationName);
		}
		String sb = sBuilder.toString();
		String sql = "select T.station_id as STATIONID,T.STATION_ADDRESS,a.area_name as PROVINCE, T.station_name  as STATION_NAME,T.station_mn as STATION_MN, a1.area_name as AERA,"
				+ " T.LATITUDE,T.LONGITUDE,T.AREA_ID,T.STATION_CLASSIFY_ID,T.STATION_TYPE_ID,T.TARGER_WATER_QUALITY,T.BASINN_ID,T.BASINN_NAME,"
				+ " T.station_river as RIVER,T.suiface_water_types as WATER_TYPE,T.sort as STATION_SORT,T.enabled as STATION_ENABLED,T.TARGER_WATER_QUALITY AS STATION_ARMLEVEL "
				+ " from STATION T left join AREA a on T.province_id = a.area_id left join AREA a1 "
				+ " on T.area_id = a1.area_id " + leftJoin.toString() + " where 1=1 " + sb + " order by T.SORT ASC";
		// 分页设置
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			Page<Map<String, Object>> page = iEntityManagerDao.findPageBySQL(sql, pageObject.getPageNumber(),
					pageObject.getPageSize());
			// Page<Map<String, Object>> result = PageUtil.inventedObjectPage(stations,
			// page);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
		} else {
			List<Map<String, Object>> stations = iEntityManagerDao.getListMapBySQL(sql);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(stations);
		}
	}

	// 如果roleId筛选，得到站点基础信息包含区域流域省份
	private List<Station> getStationBasicByroleId(HttpServletRequest request, String sqlOut, YunlAppInfoParam params) {
		List<Map<String, Object>> infos = new ArrayList<Map<String, Object>>();
		// 根据用户筛选站点
		List<Station> stations = new ArrayList<Station>();
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
		// 过滤
		// 根据用户筛选
		List<Object> sqls = iFilterService.getFilterSql(request, params);
		sBuilder = (StringBuilder) sqls.get(0);
		leftJoin = (StringBuilder) sqls.get(1);
		String sql = "select t.TARGER_WATER_QUALITY,t.station_name,t.longitude,t.latitude,t.station_address,t.build_time,t.station_leader,t.leader_tel,t.monitor_status,t.enabled,t.sort, "
				+ "t.control_level,t.station_id,t.auto_flag,t.manuel_flag,t.public_flag,t.oper_company_name,t.oper_company_leader,t.oper_company_leader_tel,t.station_leader_id, "
				+ "t.networking,t.station_mn,t.station_passworld,t.station_property,t.station_provinces_up_down,t.station_type1,t.user_id,t.enabled_time, "
				+ "t.local_mangermnet_units,t.station_river,t.station_function,t.station_brief_info,t.suiface_water_types,t.oper_company_id,t.data_frequency, "
				+ "a.area_code,a.area_name,a.aim_water_level as area_aim,a.area_id,a.parent_id,a.area_level_id,b.basinn_id,b.basinn_name,b.basinn_code,b.aim_water_level as basinn_aim, "
				+ "ty.station_type_id,ty.station_type_name,ty.station_type_code,cla.station_classify_id,cla.station_classify_name,cla.station_classify_code "
				+ "from station t left join area a on t.area_id = a.area_id left join basinn b on t.basinn_id = b.basinn_id left join station_type ty on t.station_type_id=ty.station_type_id "
				+ "left join station_classify cla on t.station_classify_id = cla.station_classify_id " + leftJoin
				+ " where 1=1 " + sBuilder.toString() + sqlOut;
		infos = iEntityManagerDao.getListMapBySQL(sql);
		// 查询站点信息
		for (Map<String, Object> map : infos) {
			Station station = new Station();
			// 区域
			Area area = new Area();
			// @Column(name="AREA_ID")
			String areaId = map.get("AREA_ID").toString();
			// 区域编码**@Column(name="AREA_CODE")
			String areaCode = map.get("AREA_CODE").toString();
			// 区域名称**@Column(name="AREA_NAME")
			String areaName = map.get("AREA_NAME").toString();
			// 父标识**name="PARENT_ID")
			String parentId = map.get("PARENT_ID").toString();
			// 区域水质目标等级**name="AIM_WATER_LEVEL")
			String aimWaterLevel = map.get("AREA_AIM") == null ? "" : map.get("AREA_AIM").toString();
			area.setAimWaterLevel(aimWaterLevel);
			area.setAreaCode(areaCode);
			area.setAreaId(areaId);
			area.setAreaName(areaName);
			area.setParentId(parentId);
			station.setArea(area);
			Basinn basinn = new Basinn();
			// @Column(name="BASINN_ID")
			String basinnId = map.get("BASINN_ID") == null ? "" : map.get("BASINN_ID").toString();
			// 流域名称**name="BASINN_NAME" ,nullable = false)
			String basinnName = map.get("BASINN_NAME") == null ? "" : map.get("BASINN_NAME").toString();
			// 流域code**name = "BASINN_CODE")
			String basinnCode = map.get("BASINN_CODE") == null ? "" : map.get("BASINN_CODE").toString();
			// 水质目标等级**name="AIM_WATER_LEVEL")
			String aimWaterLevelBasinn = map.get("BASINN_AIM") == null ? "" : map.get("BASINN_AIM").toString();
			basinn.setAimWaterLevel(aimWaterLevelBasinn);
			basinn.setBasinnCode(basinnCode);
			basinn.setBasinnId(basinnId);
			basinn.setBasinnName(basinnName);
			station.setBasinn(basinn);
			//
			String stationId = map.get("STATION_ID") == null ? "" : map.get("STATION_ID").toString();
			// 自动监测站房标识(0否1是name="AUTO_FLAG")
			Integer autoFlag = map.get("AUTO_FLAG") == null ? null
					: NumberUtils.createInteger(map.get("AUTO_FLAG").toString());
			// 建造时间 Column(name="BUILD_TIME")
			Date buildTime = map.get("BUILD_TIME") == null ? null : (Date) map.get("BUILD_TIME");
			// 站点控制等级(0国控1省控,2市控,3区控,4非控)**/Column(name="CONTROL_LEVEL")
			Integer controlorLevel = map.get("CONTROL_LEVEL") == null ? null
					: NumberUtils.createInteger(map.get("CONTROL_LEVEL").toString());
			// 是否验收 **name = "ENABLED")
			Integer enabled = map.get("ENABLED") == null ? null
					: NumberUtils.createInteger(map.get("ENABLED").toString());
			// 纬度name = "LATITUDE")
			Double latitude = map.get("LATITUDE") == null ? null
					: NumberUtils.createDouble(map.get("LATITUDE").toString());
			// 负责人电话 **/name="LEADER_TEL")
			String leaderTel = map.get("LEADER_TEL") == null ? null : map.get("LEADER_TEL").toString();
			// 经度name = "LONGITUDE")
			Double longitude = map.get("LONGITUDE") == null ? null
					: NumberUtils.createDouble(map.get("LONGITUDE").toString());
			// 手动监测站房标识(0否1是) **/name="MANUEL_FLAG")
			Integer manuelFlag = map.get("MANUEL_FLAG") == null ? null
					: NumberUtils.createInteger(map.get("MANUEL_FLAG").toString());
			// 是否视频监控 0否1是*name="MONITOR_STATUS")
			Integer monitorStatus = map.get("MONITOR_STATUS") == null ? null
					: NumberUtils.createInteger(map.get("MONITOR_STATUS").toString());
			// 运维公司负责人 **name="OPER_COMPANY_LEADER")
			@SuppressWarnings("unused")
			String operCompanyLeader = map.get("OPER_COMPANY_LEADER") == null ? ""
					: map.get("OPER_COMPANY_LEADER").toString();
			// ** 运维公司负责人电话 **name="OPER_COMPANY_LEADER_TEL")
			String operCompanyLeaderTel = map.get("OPER_COMPANY_LEADER_TEL") == null ? ""
					: map.get("OPER_COMPANY_LEADER_TEL").toString();
			// 运维公司名称 **name="OPER_COMPANY_NAME")
			String operCompanyName = map.get("OPER_COMPANY_NAME") == null ? ""
					: map.get("OPER_COMPANY_NAME").toString();
			// 运维公司id name="OPER_COMPANY_ID")
			String operCompanyId = map.get("OPER_COMPANY_ID") == null ? "" : map.get("OPER_COMPANY_ID").toString();
			// 是否对外公开(0否1是,有的站点只能环保局人查看* 部分站点数据公众可以看) **/name="PUBLIC_FLAG")
			Integer publicFlag = map.get("PUBLIC_FLAG") == null ? null
					: NumberUtils.createInteger(map.get("PUBLIC_FLAG").toString());
			// 站点排序s **name="SORT")
			Integer sort = map.get("SORT") == null ? null : NumberUtils.createInteger(map.get("SORT").toString());
			// 站点分类 **name = "STATION_TYPE_ID")
			StationType stationType = new StationType();
			// Column(name="STATION_TYPE_ID")
			String stationTypeId = map.get("STATION_TYPE_ID") == null ? "" : map.get("STATION_TYPE_ID").toString();
			// 类型编号**name="STATION_TYPE_CODE")
			String stationTypeCode = map.get("STATION_TYPE_CODE") == null ? ""
					: map.get("STATION_TYPE_CODE").toString();
			// 站点类型名称**name="STATION_TYPE_NAME")
			String stationTypeName = map.get("STATION_TYPE_NAME") == null ? ""
					: map.get("STATION_TYPE_NAME").toString();
			stationType.setStationTypeCode(stationTypeCode);
			stationType.setStationTypeId(stationTypeId);
			stationType.setStationTypeName(stationTypeName);
			station.setStationType(stationType);
			//
			// 负责人信息id
			String stationLeaderId = map.get("STATION_LEADER_ID") == null ? ""
					: map.get("STATION_LEADER_ID").toString();
			// 站点负责人 **name="STATION_LEADER")
			String stationLeader = map.get("STATION_LEADER") == null ? "" : map.get("STATION_LEADER").toString();
			// 站点名称 **name="STATION_NAME")
			String stationName = map.get("STATION_NAME") == null ? "" : map.get("STATION_NAME").toString();
			// 是否联网0否1是**name = "NETWORKING")
			Integer networking = map.get("NETWORKING") == null ? null
					: NumberUtils.createInteger(map.get("NETWORKING").toString());
			// 站点mn**name = "STATION_MN")
			String stationMn = map.get("STATION_MN") == null ? "" : map.get("STATION_MN").toString();
			// 站点密码**name = "STATION_PASSWORLD")
			String stationPassworld = map.get("STATION_PASSWORLD") == null ? ""
					: map.get("STATION_PASSWORLD").toString();
			// 站点属性**name = "STATION_PROPERTY")
			String stationProperty = map.get("STATION_PROPERTY") == null ? "" : map.get("STATION_PROPERTY").toString();
			// 上下游省份**name = "STATION_PROVINCES_UP_DOWN")
			String stationProvincesUpDown = map.get("STATION_PROVINCES_UP_DOWN") == null ? ""
					: map.get("STATION_PROVINCES_UP_DOWN").toString();
			// 站点类型1（污染源，水站） **name = "STATION_TYPE1")
			String stationType1 = map.get("STATION_TYPE1") == null ? "" : map.get("STATION_TYPE1").toString();
			// 目标水质 **name = "TARGER_WATER_QUALITY")
			String targerWaterQuality = map.get("TARGER_WATER_QUALITY") == null ? ""
					: map.get("TARGER_WATER_QUALITY").toString();
			// 验收时间*name = "ENABLED_TIME")
			String enableTime = map.get("ENABLED_TIME") == null ? "" : map.get("ENABLED_TIME").toString();
			// 当地管理单位*name = "LOCAL_MANGERMNET_UNITS")
			// 站点类别*name = "STATION_CLASSIFY_ID")
			StationClassify stationClassify = new StationClassify();
			// Column(name="STATION_CLASSIFY_ID")
			String stationClassifyId = map.get("STATION_CLASSIFY_ID") == null ? ""
					: map.get("STATION_CLASSIFY_ID").toString();
			// 类别编码**name="STATION_CLASSIFY_CODE")
			String stationClassifyCode = map.get("STATION_CLASSIFY_CODE") == null ? ""
					: map.get("STATION_CLASSIFY_CODE").toString();
			// 类别名称**name="STATION_CLASSIFY_NAME")
			String stationClassifyName = map.get("STATION_CLASSIFY_NAME") == null ? ""
					: map.get("STATION_CLASSIFY_NAME").toString();
			stationClassify.setStationClassifyCode(stationClassifyCode);
			stationClassify.setStationClassifyId(stationClassifyId);
			stationClassify.setStationClassifyName(stationClassifyName);
			station.setStationClassify(stationClassify);
			//
			// 站点所属河流*name = "STATION_RIVER")
			String stationRiver = map.get("STATION_RIVER") == null ? "" : map.get("STATION_RIVER").toString();
			// 断面功能(name = "STATION_FUNCTION")
			String stationFunction = map.get("STATION_FUNCTION") == null ? "" : map.get("STATION_FUNCTION").toString();
			// 断面功能name = "SUIFACE_WATER_TYPES"
			String suifaceWaterTypes = map.get("SUIFACE_WATER_TYPES") == null ? ""
					: map.get("SUIFACE_WATER_TYPES").toString();
			// 数据发送频率S秒M分钟H小时name = "DATA_FREQUENCY")
			String dataFrequency = map.get("DATA_FREQUENCY") == null ? "" : map.get("DATA_FREQUENCY").toString();
			// name = "LOCAL_MANGERMNET_UNITS")
			String localMangermnetUnits = map.get("LOCAL_MANGERMNET_UNITS") == null ? ""
					: map.get("LOCAL_MANGERMNET_UNITS").toString();
			station.setAutoFlag(autoFlag);
			station.setBuildTime(buildTime);
			station.setControlorLevel(controlorLevel);
			station.setDataFrequency(dataFrequency);
			station.setEnabled(enabled);
			station.setEnableTime(enableTime);
			station.setLatitude(latitude);
			station.setLeaderTel(leaderTel);
			station.setLocalMangermnetUnits(localMangermnetUnits);
			station.setLongitude(longitude);
			station.setManuelFlag(manuelFlag);
			station.setMonitorStatus(monitorStatus);
			station.setNetworking(networking);
			station.setOperCompanyId(operCompanyId);
			station.setOperCompanyLeader(operCompanyLeaderTel);
			station.setOperCompanyName(operCompanyName);
			station.setPublicFlag(publicFlag);
			station.setSort(sort);
			station.setStationFunction(stationFunction);
			station.setStationId(stationId);
			station.setStationLeader(stationLeader);
			station.setStationMn(stationMn);
			station.setStationName(stationName);
			station.setStationPassworld(stationPassworld);
			station.setStationProperty(stationProperty);
			station.setStationProvincesUpDown(stationProvincesUpDown);
			station.setStationRiver(stationRiver);
			station.setStationType1(stationType1);
			station.setSuifaceWaterTypes(suifaceWaterTypes);
			station.setTargerWaterQuality(targerWaterQuality);
			station.setStationLeaderId(stationLeaderId);
			stations.add(station);
		}
		return stations;
	}

	public ResultEntity queryByUserId(HttpServletRequest request) {
		List<Map<String, Object>> infos = new ArrayList<Map<String, Object>>();
		// 根据用户筛选站点
		List<String> ids = iFilterService.getStationIdByCookie(request);
		if (ids != null) {
			infos = iStationRepository.getStationMnBasicById(ids);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(infos);
	}

	///////////////////////////////
	/****/
	@SuppressWarnings(value = { "serial" })
	public List<Station> treeUtilBYpower(String platfrom, String appCode) {
		List<Station> stations =
				// iStationRepository.findAll();
				iStationVievRepository.findAll(new Specification<Station>() {
					public Predicate toPredicate(Root<Station> root, CriteriaQuery<?> query,
							CriteriaBuilder criteriaBuilder) {
						List<Predicate> predicates = new ArrayList<Predicate>();
						return query.where(predicates.toArray(new Predicate[predicates.size()]))
								.orderBy(criteriaBuilder.asc(root.get("stationMn"))).getRestriction();
					}
				});
		if (StringUtils.isNotBlank(platfrom)) {
			List<String> ids = platformCustomerStationRepository.findByPlatformId(platfrom).stream()
					.map(m -> m.getStationId()).collect(Collectors.toList());
			if (ids.size() > 0) {
				stations = stations.stream().filter(f -> ids.contains(f.getStationId())).collect(Collectors.toList());
			}
		} else {
			List<String> ids = iStationAndAppRepository.findByAppCode(appCode).stream().map(m -> m.getStationId())
					.collect(Collectors.toList());
			if (ids.size() > 0) {
				stations = stations.stream().filter(f -> ids.contains(f.getStationId())).collect(Collectors.toList());
			}
		}
		return stations;
	}

	public ResultEntity queryTreeByPlatform(String platfrom, String appCode) {
		List<Station> stations = treeUtilBYpower(platfrom, appCode);// 通过条件的到站点
		if (stations == null || stations.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.NO_STATION_OBJECT).setDataList(null);
		}
		// 得到站点对应区域的code
		List<String> areaCodes = stations.stream().map(l -> l.getArea().getAreaCode()).collect(Collectors.toList());
		// 拿到站点对应区域的所有区域和父区域
		// List<Area> areas = iAreaRespository.findByAreaCodeIn(areaCodes);
		List<Area> areas = iAreaService.areaParents(String.join(",", areaCodes));
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		// 地区没有父节点的做根结点
		for (Area area : areas) {
			// 如果没有父节点getParentId做根结点
			if (StringUtils.isBlank(area.getParentId())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setNodeId(area.getAreaCode());
				stationTreeVO.setNodeName(area.getAreaName());
				stationTreeVO.setIsStation(false);
				stationTreeVO.setNodeType("area");
				stationTreeVO.setStructureType(area.getAreaLevel().getAreaLevelCode());
				stationTreeVO.setStationId(area.getAreaCode());
				rootList.add(stationTreeVO);
				// 如果有getParentId放到非根节点
			} else {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(area.getParentId());
				stationTreeVO.setNodeId(area.getAreaCode());
				stationTreeVO.setNodeName(area.getAreaName());
				stationTreeVO.setIsStation(false);
				stationTreeVO.setNodeType("area");
				stationTreeVO.setStationId(area.getAreaCode());
				stationTreeVO.setStructureType(area.getAreaLevel().getAreaLevelCode());
				bodyList.add(stationTreeVO);
			}
		}
		// 把站点放入集合
		for (Station station : stations) {
			// 确保站点有对应的流域
			if (StringUtils.isNotBlank(station.getArea().getAreaCode())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(station.getArea().getAreaCode());
				stationTreeVO.setNodeId(station.getStationMn());
				stationTreeVO.setNodeName(station.getStationName());
				stationTreeVO.setIsStation(true);
				stationTreeVO.setNodeType("station");
				stationTreeVO.setNetworking(station.getNetworking());
				stationTreeVO.setEnabled(station.getEnabled().intValue());
				stationTreeVO.setStationId(station.getStationId());
				// 默认无视频监控
				int monitorStatus = station.getMonitorStatus() == null ? 0 : station.getMonitorStatus().intValue();
				stationTreeVO.setMonitorStatus(monitorStatus);
				stationTreeVO.setStructureType(AreaEnum.STATION.getResoString());
				stationTreeVO.setStationType1(station.getStationType1());
				stationTreeVO.setTargerWaterQuality(station.getTargerWaterQuality());
				stationTreeVO.setAreaCode(station.getArea().getAreaCode());
				stationTreeVO.setAreaName(station.getArea().getAreaName());
				stationTreeVO.setBasinCode(station.getBasinn().getBasinnCode());
				stationTreeVO.setBasinName(station.getBasinn().getBasinnName());
				bodyList.add(stationTreeVO);
			}
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity queryAllAirStationInfo(HttpServletRequest request) throws Exception {
		// List<Station> stations = queryStationTreeUtil("", "", "1", "",roleId);//
		// 通过条件的到站点
		List<Station> stations = getStationBasicByroleId(request, "", null);
		String mns = "";
		List<MultiStatisVO> result = new ArrayList<>();
		MultiStatisVO vo = null;
		for (Station station : stations) {
			vo = new MultiStatisVO();
			mns += station.getStationMn() + ",";
			vo.setName(station.getStationName());
			vo.setLat(station.getLatitude());
			vo.setLng(station.getLongitude());
			vo.setStationMn(station.getStationMn());
			vo.setTargetQualityLevel(station.getTargerWaterQuality());
			result.add(vo);
		}
		if (mns.length() > 1) {
			mns = mns.substring(0, mns.length() - 1);
		}
		ResultEntity res = statisticsAndAlarm.queryHourDataAir(mns, "all");
		List<AirInstructionsDataDto> waterList = objectMapperUtil.convertList(res, AirInstructionsDataDto.class);
		Map<String, AirInstructionsDataDto> waterMap = new HashMap<>();
		for (AirInstructionsDataDto data : waterList) {
			waterMap.put(data.getMn(), data);
		}
		AirInstructionsDataDto data = null;
		for (MultiStatisVO multiStatisVO : result) {
			data = waterMap.get(multiStatisVO.getStationMn());
			if (data == null)
				continue;
			multiStatisVO.setAqi(data.getAqi());
			multiStatisVO.setEvaluation(data.getEvaluation());
			multiStatisVO.setPrimaryPollutant(data.getPrimaryPollutant());
			multiStatisVO.setTime(data.getDataTime());
			multiStatisVO.setWaterQualityLevel(data.getWaterQuality());
		}

		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(result);
	}

	public List<StationTypeListVO> packAirStatonTypeListVP(HttpServletRequest request) throws Exception {
		// List<Station> stations = queryStationTreeUtil("", "", "1", "",roleId);//
		// 通过条件的到站点
		List<Station> stations = getStationBasicByroleId(request, "", null);
		String mns = "";
		for (Station station : stations) {
			mns += station.getStationMn() + ",";
		}
		if (mns.length() > 1) {
			mns = mns.substring(0, mns.length() - 1);
		}
		if (mns.length() == 0) {
			return null;
		}
		// ResultEntity res = iDataReceivingService.queryRowToColRealTimeData(mns, "1",
		// "100000");
		// Page<WaterInstructionsDataDto> page = objectMapperUtil.convertPage(res,
		// WaterInstructionsDataDto.class);
		ResultEntity res = statisticsAndAlarm.queryHourDataAir(mns, "all");
		List<AirInstructionsDataDto> dataList = objectMapperUtil.convertList(res, AirInstructionsDataDto.class);
		// List<WaterInstructionsDataDto> dataList = page.getList();
		Map<String, AirInstructionsDataDto> dataMap = new HashMap<>();
		for (AirInstructionsDataDto dto : dataList) {
			dataMap.put(dto.getMn(), dto);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		List<StationTypeListVO> list = new ArrayList<>();
		int all = 0;
		int normal = 0;
		int dataabnormal = 0;
		int linkabnormal = 0;
		AirInstructionsDataDto dto = null;
		for (Station mv : stations) {
			String mn = mv.getStationMn();
			dto = dataMap.get(mn);
			if (dto == null) {
				linkabnormal++;
				continue;
			}
			boolean zc = true;
			try {
				if (dto.getDataTime() == null) {
					linkabnormal++;
					continue;
				}
				Date cDate = sdf.parse(dto.getDataTime());
				long ctimel = cDate.getTime();
				long timel = date.getTime();
				if (((timel - ctimel) / 1000) > 3600 * 8) {
					linkabnormal++;
					zc = false;
					continue;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String state = dto.getStationState();
			state = getStateAir(dto.getAqi());
			if ("2".equals(state)) {
				dataabnormal++;
				zc = false;
			}
			if (zc) {
				normal++;
			}
		}
		if (stations != null) {
			all = stations.size();
			StationTypeListVO rall = new StationTypeListVO();
			rall.setName("全部");
			rall.setNumber(all);
			rall.setType("all");

			StationTypeListVO rnormal = new StationTypeListVO();
			rnormal.setName("达标");
			rnormal.setNumber(normal);
			rnormal.setType("normal");

			StationTypeListVO rdataabnormal = new StationTypeListVO();
			rdataabnormal.setName("未达标");
			rdataabnormal.setNumber(dataabnormal);
			rdataabnormal.setType("dataAnomaly");

			StationTypeListVO rlinkabnormal = new StationTypeListVO();
			rlinkabnormal.setName("联网异常");
			rlinkabnormal.setNumber(linkabnormal);
			rlinkabnormal.setType("networkAnomaly");
			list.add(rall);
			list.add(rnormal);
			list.add(rdataabnormal);
			list.add(rlinkabnormal);

		}
		return list;
	}

	public List<MainStatisVO> allAirCateStatis(StatisDataQueryVO statisData, String statusType,
			HttpServletRequest request) throws Exception {
		List<MainStatisVO> mainList = null;
		Map<String, MainStatisVO> mainMap = new HashMap<>();
		// 得到站点信息
		// List<Station> stations = queryStationTreeUtil("", "", "1", "",roleId);//
		// 通过条件的到站点
		List<Station> stations = getStationBasicByroleId(request, "", null);
		String mns = "";
		for (Station station : stations) {
			mns += station.getStationMn() + ",";
		}
		if (mns.length() > 1) {
			mns = mns.substring(0, mns.length() - 1);
		}
		if (mns.length() == 0) {
			return mainList;
		}
		// ResultEntity res = iDataReceivingService.queryRowToColRealTimeData(mns, "1",
		// "100000");
		// Page<WaterInstructionsDataDto> page = objectMapperUtil.convertPage(res,
		// WaterInstructionsDataDto.class);
		// List<WaterInstructionsDataDto> list = page.getList();
		ResultEntity res = statisticsAndAlarm.queryHourDataAir(mns, "all");
		List<AirInstructionsDataDto> list = objectMapperUtil.convertList(res, AirInstructionsDataDto.class);
		Map<String, AirInstructionsDataDto> dataMap = new HashMap<>();
		for (AirInstructionsDataDto dto : list) {
			dataMap.put(dto.getMn(), dto);
		}
		Basinn basinn = null;
		AirInstructionsDataDto data = null;
		Area area = null;
		String areaId = null;
		MainStatisVO main = null;
		String basinnId = null;
		List<MultiStatisVO> multiStatisVOs = null;
		MultiStatisVO stationVO = null;
		String queryType = statisData.getQueryType();
		String id = null, name = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (Station station : stations) {
			basinn = station.getBasinn();
			area = station.getArea();
			areaId = area.getAreaId();
			basinnId = basinn.getBasinnId();
			if ("area".equals(queryType)) {
				id = areaId;
				name = area.getAreaName();
			} else if ("river".equals(queryType)) {
				id = basinnId;
				name = basinn.getBasinnName();
			} else {
				continue;
			}
			data = dataMap.get(station.getStationMn());
			stationVO = new MultiStatisVO();
			stationVO.setName(station.getStationName());
			stationVO.setStationType(station.getStationType1());
			stationVO.setWaterQualityIndex(0.95);
			stationVO.setArea(station.getArea().getAreaName());
			stationVO.setRiver(basinn.getBasinnName());
			stationVO.setStationMn(station.getStationMn());
			stationVO.setLat(station.getLatitude());
			stationVO.setLng(station.getLongitude());
			if (data != null) {
				stationVO.setTime(data.getDataTime());
				stationVO.setEvaluation(data.getEvaluation());
				stationVO.setWaterQualityLevel(data.getWaterQuality());
				stationVO.setPrimaryPollutant(data.getPrimaryPollutant());
				stationVO.setAqi(data.getAqi());
				stationVO.setStationState(data.getStationState());
			}
			data.setStationState(getStateAir(data.getAqi()));
			Date cDate = null;
			boolean bool = false;
			if (data != null && data.getDataTime() != null) {
				try {
					cDate = sdf.parse(data.getDataTime());
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if (statusType.equals("all")) {
				bool = true;
			} else if (statusType.equals("normal")) {
				if (data != null && data.getStationState().equals("1")) {
					if (cDate != null && ((date.getTime() - cDate.getTime()) / 1000) <= 3600 * 8) {
						bool = true;
					}
				}
			} else if (statusType.equals("dataAnomaly")) {
				if (data != null && data.getStationState().equals("2")) {
					if (cDate != null && ((date.getTime() - cDate.getTime()) / 1000) <= 3600 * 8) {
						bool = true;
					}
				}
			} else if (statusType.equals("networkAnomaly")) {
				if (data == null || cDate == null || ((date.getTime() - cDate.getTime()) / 1000) > 3600 * 8) {
					bool = true;
				}
			}
			if (!bool) {
				continue;
			}
			if (mainMap.get(id) == null) {
				main = new MainStatisVO();
				main.setCount(1);
				multiStatisVOs = new ArrayList<>();
				multiStatisVOs.add(stationVO);
				main.setMultiStatisVOs(multiStatisVOs);
				main.setName(name);
				if (data != null) {
					main.setEvaluation(data.getEvaluation());
				}
				mainMap.put(id, main);
			} else {
				mainMap.get(id).setCount(mainMap.get(id).getCount() + 1);
				mainMap.get(id).getMultiStatisVOs().add(stationVO);
			}

		}
		mainList = new ArrayList<>(mainMap.values());
		return mainList;
	}

	private String getStateAir(int AQI) {
		String airquality = "0";
		if (AQI >= 0 && AQI <= 50) {
			airquality = "1";
		} else if (AQI >= 51 && AQI <= 100) {
			airquality = "1";
		} else if (AQI >= 101 && AQI <= 150) {
			airquality = "2";
		} else if (AQI >= 151 && AQI <= 200) {
			airquality = "2";
		} else if (AQI >= 201 && AQI <= 300) {
			airquality = "2";
		} else if (AQI > 300) {
			airquality = "2";
		}
		return airquality;
	}

	public ResultEntity queryStationByOfcId(HttpServletRequest request, String ofcId, String key) {
		String sqlAnd = "";
		if (StringUtils.isNotBlank(key)) {
			sqlAnd = " and t.station_name like '%" + key + "%' ";
		}
		List<Station> stations = getStationBasicByroleId(request, sqlAnd, null);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(stations);
	}

	public ResultEntity queryStationStute(HttpServletRequest request) {
		List<StationGisVo> list = new ArrayList<StationGisVo>();
		// 查询所有运维分公司
		ResultEntity result = identityManagement.getTBranchOfcs(null, null, null);
		List<TBranchOfc> tBranchOfcs = objectMapperUtil.convertList(result, TBranchOfc.class);
		Map<String, TBranchOfc> tBranchMap = new HashMap<String, TBranchOfc>();
		for (TBranchOfc tBranchOfc : tBranchOfcs) {
			tBranchMap.put(tBranchOfc.getId(), tBranchOfc);
		}
		// 查询站点
		List<Station> stations = getStationBasicByroleId(request, "", null);
		Map<String, List<Station>> glist = stations.stream().collect(Collectors.groupingBy(g -> g.getOperCompanyId()));
		List<String> ofcIds = stations.stream().map(m -> m.getOperCompanyId()).distinct().collect(Collectors.toList());
		// 封装每个分公司
		for (String ofcId : ofcIds) {
			TBranchOfc tBranchOfc = tBranchMap.get(ofcId);
			if (tBranchOfc == null) {
				continue;
			}
			List<Station> thisOfcList = glist.get(ofcId);
			StationGisVo stationGisVo = new StationGisVo();
			stationGisVo.setOpsId(tBranchOfc.getId());
			stationGisVo.setOpsName(
					tBranchOfc.getBranchName() + " (" + tBranchOfc.getPerChg() + " " + tBranchOfc.getPerPhone() + ")");
			Map<String, Object> flag = new HashMap<String, Object>();
			flag.put("sum", thisOfcList.size());
			flag.put("online", 0);
			flag.put("disOnline", thisOfcList.size());
			flag.put("alarm", 0);
			stationGisVo.setStatus(flag);
			list.add(stationGisVo);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	public ResultEntity queryStationOnly(HttpServletRequest request, String typeId, PageObject pageObject) {
		final String type = typeId;
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
		// 过滤
		// 根据用户筛选
		List<Object> sqls = iFilterService.getFilterSql(request, null);
		sBuilder = (StringBuilder) sqls.get(0);
		leftJoin = (StringBuilder) sqls.get(1);
		List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		Page<Map<String, Object>> page = new Page<Map<String, Object>>();
		String sql = "";
		// 分类别查询
		String whereSql = "";
		if (StringUtils.isNotBlank(type)) {
			whereSql = " and t.station_type_id = '" + type + "' ";
			sql = "select t.station_address,t.station_type_id,t.basinn_name,t.station_name,t.station_id,"
					+ "t.station_mn,t.area_names,t.province_name," + "t.targer_water_quality from STATION t "
					+ leftJoin.toString() + " where 1=1 " + "" + sBuilder.toString() + " " + whereSql + " ";
//			sql = "select t.station_address,t.station_type_id,t.basinn_name,t.station_name,t.station_id,t.station_mn,t.area_names,t.province_name,"
//					+ "t.targer_water_quality,ps.project_code from STATION t left join project_and_station ps"
//					+ " on ps.station_code = t.station_mn " + leftJoin.toString() + " where 1=1 " + ""
//					+ sBuilder.toString() + " " + whereSql + " ";
		} else {
			sql = "select t.station_address,t.station_type_id,t.basinn_name,t.station_name,t.station_id,t.station_mn,t.area_names,t.province_name,"
					+ "t.targer_water_quality from station t " + leftJoin.toString() + " where 1=1 " + ""
					+ sBuilder.toString() + "";
		}
		// 因子信息
		String indexType = "";
		if ("2c9212e66f0241df016f1659ce77001f".equals(type)) {// 空气
			indexType = " and t.project_type_id = '2c9212e66f0241df016f1659ce77001f'";
		} else if ("2c9212e66f323a55016f59867a200030".equals(type)) {// 水
			indexType = " and t.project_type_id = '2c9212e66f323a55016f59867a200030'";
		} else if ("2c9212e66f0241df016f1659ce723467".equals(type)) {// 烟气
			indexType = " and t.project_type_id = '2c9212e66f0241df016f1659ce723467'";
		}
		String indexSql = "select * from project t where 1=1 and t.project_type_id"
				+ " not in ('40282bb16a4400b9016a440107270011','2240282bb16a4400b9016a4401072705') " + indexType + "";
		List<Map<String, Object>> projects = iEntityManagerDao.getListMapBySQL(indexSql);
		// 分页判断
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			page = iEntityManagerDao.findPageBySQL(sql, pageObject.getPageNumber(), pageObject.getPageSize());
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page).setInfo(projects);
		} else {
			datas = iEntityManagerDao.getListMapBySQL(sql);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(datas).setInfo(projects);
		}

	}

	@Override
	public List<StationYunlInfoDto> queryBaiscStationInfo(YunlAppInfoParam param, String type) {
		// type = "WQ07,WQ08";
		if (StringUtils.isNotBlank(type)) {
			List<String> types = ArrayUtils.stringToList(type);
			type = ArrayUtils.convertListToString(types);
			if (StringUtils.isNotBlank(type)) {
				type = " and t.station_type_id in (" + type + ")";
			}
		} else {
			type = "";
		}
		String mns = param.getMns();
		if (StringUtils.isNotBlank(mns)) {
			List<String> types = ArrayUtils.stringToList(mns);
			String type2 = ArrayUtils.convertListToString(types);
			if (StringUtils.isNotBlank(type2)) {
				type += " and t.station_mn in (" + type2 + ")";
			}
		}
		String name = param.getName();
		if (StringUtils.isNotBlank(name)) {
			type += " and t.station_name like '%" + name + "%' ";
		}
		List<Station> list = getStationBasicByroleId(null, type, param);
		return list.stream().map(entityObjectMapper::station2InfoDto).collect(Collectors.toList());
	}

	@Override
	public ResultEntity queryStationAndTypeTree(String keyName, String typeCode, String isUsedString,
			String isMonitoring, HttpServletRequest request) {
		List<Map<String, Object>> stations = treeAreaUtilBySql(keyName, typeCode, isUsedString, isMonitoring, request);// 通过条件的到站点
		if (stations == null || stations.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.NO_STATION_OBJECT).setDataList(null);
		}
		// 得到站点对应区域的code
		List<String> stationTypes = stations.stream().map(l -> l.get("STATION_TYPE_ID").toString()).distinct()
				.collect(Collectors.toList());
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		List<StationType> stationTypeList = stationTypeRespository.findByStationTypeIdIn(stationTypes);
		for (StationType stationType : stationTypeList) {
			StationTreeVO stationTreeVO = new StationTreeVO();
			stationTreeVO.setNodeId(stationType.getStationTypeId());
			stationTreeVO.setNodeName(stationType.getStationTypeName());
			stationTreeVO.setIsStation(false);
			stationTreeVO.setNodeType("sType");
			stationTreeVO.setStructureType("1");
			stationTreeVO.setStationId(stationType.getStationTypeId());
			rootList.add(stationTreeVO);
		}
		// 把站点放入集合
		for (Map<String, Object> station : stations) {
			// 确保站点有对应的流域
			if (StringUtils.isNotBlank(station.get("AREA_CODE").toString())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(station.get("AREA_CODE").toString());
				stationTreeVO.setNodeId(station.get("STATION_MN").toString());
				stationTreeVO.setNodeName(station.get("STATION_NAME").toString());
				stationTreeVO.setIsStation(true);
				stationTreeVO.setNodeType("station");
				stationTreeVO.setNetworking(Integer.parseInt(station.get("NETWORKING").toString()));
				stationTreeVO.setEnabled(Integer.parseInt(station.get("ENABLED").toString()));
				stationTreeVO.setStationId(station.get("STATION_ID").toString());
				// 默认无视频监控
				stationTreeVO.setMonitorStatus(Integer.parseInt(station.get("MONITOR_STATUS").toString()));
				stationTreeVO.setStructureType(AreaEnum.STATION.getResoString());
				stationTreeVO.setStationType1(station.get("STATION_TYPE_ID").toString());
				stationTreeVO.setTargerWaterQuality(station.get("TARGER_WATER_QUALITY").toString());
				stationTreeVO.setAreaCode(station.get("AREA_CODE").toString());
				stationTreeVO.setAreaName(station.get("AREA_NAME").toString());
				stationTreeVO.setDeviceSerial(
						station.get("DEVICE_SERIAL") == null ? "" : station.get("DEVICE_SERIAL").toString());
//              stationTreeVO.setBasinCode(station.get("BASINN").toString());
//              stationTreeVO.setBasinName(station.get("AREA_CODE").toString());
				bodyList.add(stationTreeVO);
			}
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTypeTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
//      
	}

	@Override
	public ResultEntity queryStationAndItemTree(String keyName, String typeCode, String isUsedString,
			String isMonitoring, HttpServletRequest request) {
		List<Map<String, Object>> stations = treeItemUtilBySql(keyName, typeCode, isUsedString, isMonitoring, request);// 通过条件的到站点
		if (stations == null || stations.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.NO_STATION_OBJECT).setDataList(null);
		}
		List<String> ids = stations.stream().map(l -> l.get("STATION_ID").toString()).distinct()
				.collect(Collectors.toList());
		List<Item> items = itemRepository.queryByStationId(ids);
//		List<ItemAndStation> itemAndStations = itemAndStationRepository.findByStationIdIn(ids);
//		Map<String, String> itemStationMap = new HashMap<String, String>();
//		for (ItemAndStation itemAndStation : itemAndStations) {
//			itemStationMap.put(itemAndStation.getStationId(), itemAndStation.getItemId());
//		}
		List<StationTreeVO> bodyList = new ArrayList<StationTreeVO>();// 保存除根结点（也可包含）其他节点
		List<StationTreeVO> rootList = new ArrayList<StationTreeVO>();// 保存根节点
		for (Item item : items) {
			// 如果没有父节点getParentId做根结点
			if (StringUtils.isBlank(item.getParientId())) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setNodeId(item.getId());
				stationTreeVO.setNodeName(item.getName());
				stationTreeVO.setIsStation(false);
				stationTreeVO.setNodeType("item");
				rootList.add(stationTreeVO);
				// 如果有getParentId放到非根节点
			} else {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(item.getParientId());
				stationTreeVO.setNodeId(item.getId());
				stationTreeVO.setNodeName(item.getName());
				stationTreeVO.setIsStation(false);
				stationTreeVO.setNodeType("item");
				bodyList.add(stationTreeVO);
			}
		}
		// 把站点放入集合
		for (Map<String, Object> station : stations) {
			// String stationId = station.get("STATION_ID").toString();
			// 确保站点有对应的流域
			if (station.get("ITEM_ID") != null) {
				StationTreeVO stationTreeVO = new StationTreeVO();
				stationTreeVO.setPid(station.get("ITEM_ID").toString());
				stationTreeVO.setNodeId(station.get("STATION_MN").toString());
				stationTreeVO.setNodeName(station.get("STATION_NAME").toString());
				stationTreeVO.setIsStation(true);
				stationTreeVO.setNodeType("station");
				stationTreeVO.setNetworking(Integer.parseInt(station.get("NETWORKING").toString()));
				stationTreeVO.setEnabled(Integer.parseInt(station.get("ENABLED").toString()));
				stationTreeVO.setStationId(station.get("STATION_ID").toString());
				// 默认无视频监控
				stationTreeVO.setMonitorStatus(Integer.parseInt(station.get("MONITOR_STATUS").toString()));
				stationTreeVO.setStructureType(AreaEnum.STATION.getResoString());
				stationTreeVO.setStationType1(station.get("STATION_TYPE_ID").toString());
				stationTreeVO.setTargerWaterQuality(station.get("TARGER_WATER_QUALITY").toString());
				stationTreeVO.setAreaCode(station.get("AREA_CODE").toString());
				stationTreeVO.setAreaName(station.get("AREA_NAME").toString());
				stationTreeVO.setDeviceSerial(
						station.get("DEVICE_SERIAL") == null ? "" : station.get("DEVICE_SERIAL").toString());
				bodyList.add(stationTreeVO);
			}
		}
		// 生成树，rootList包含根结点的集合，bodyList除根节点以外的集合
		TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
		List<StationTreeVO> list = utils.getTree();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	/** 查询项目树数据 **/
	List<Map<String, Object>> treeItemUtilBySql(String keyName, String typeCode, String isUsedString,
			String isMonitoring, HttpServletRequest request) {
		List<Map<String, Object>> infos = new ArrayList<Map<String, Object>>();
		// 根据用户筛选站点
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
		// 模糊查询站点名
		if (StringUtils.isNotBlank(keyName)) {
			sBuilder.append(" and T.station_name like '%" + keyName + "%' ");
		}
		// 已建/验收使用
		if (StringUtils.isNotBlank(isUsedString)) {
			sBuilder.append(" and T.enabled = (" + isUsedString + ") ");
		}
		// 是否视频监控
		if (StringUtils.isNotBlank(isMonitoring)) {
			sBuilder.append(" and and T.monitor_status =(" + isMonitoring + ") ");
		}
		// 判断水质站与空气站 WQ\MM
		if (StringUtils.isNotBlank(typeCode)) {
			sBuilder.append(" and T.STATION_CLASSIFY_ID =\"" + typeCode + "\"");
		}
		// 过滤
		List<Object> sqls = iFilterService.getFilterSql(request, null);
		StringBuilder sBuilder2 = (StringBuilder) sqls.get(0);
		sBuilder2.append(sBuilder);
		leftJoin = (StringBuilder) sqls.get(1);
		String sql = "select it.item_id,T.station_name,T.station_mn,T.station_id,T.targer_water_quality,T.monitor_status,"
				+ "T.NETWORKING,T.enabled,T.station_type_id,a.area_id,a.area_code,a.parent_id,a.area_name,"
				+ "T.DEVICE_SERIAL from station T " + "left join area a on T.area_id = a.area_id "
				+ " left join item_and_station it on it.station_id = t.station_id " + leftJoin.toString()
				+ " where 1=1 " + " " + sBuilder2.toString() + " ";
		infos = iEntityManagerDao.getListMapBySQL(sql);
		return infos;
	}

	@Override
	public ResultEntity queryBaiscStationInfoById(String id) {
		List<String> list = iStationRepository.queryBaiscStationInfoById(id);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	@Override
	public ResultEntity queryUserIdByStationMn(String mn) {
		List<String> list = iStationRepository.queryUserIdByStationMn(mn);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

	@Override
	public ResultEntity queryStationInfo() {
		List<String> list = iStationRepository.queryStationInfo();
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

}
